append、appendTo的使用方式

本文详细介绍了JavaScript中利用DOM操作实现元素插入与修改的方法,并通过jQuery库演示了简化这些操作的过程。包括如何在特定索引处添加内容、使用jQuery进行元素追加、前置、插入、替换等技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">

<html>

  <head>

    <title>append</title>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

    <script type="text/javascript" src="jquery-1.7.1.js"></script>

<script type="text/javascript">

$(function() {

$('div').append(function(index, html) {

//index即选择器的索引

if(index == 1) {

//返回的内容即是在相应索引下的对象内部(最后)添加的内容

return '<strong>world</strong>';

}

if(index == 3) {

return 'morning';

}

});

//在每个匹配的选择器内部(最后)添加内容

$('.next').append('<strong>morning</strong>.');

//把每个匹配的元素添加的每个选择器内部

$('.foo').appendTo('p');

//还有一些相近的方法prependTo, insertBefore, insertAfter, 和 replaceAll,使用方式都差不多

});

</script>

  </head>

  

  <body>

    <div style="border: 1px solid red;width: 80px;height: 30px;">hello</div>

    <div style="border: 1px solid green;width: 80px;height: 30px;"></div>

    

    <div style="border: 1px solid red;width: 80px;height: 30px;">good</div>

    <div style="border: 1px solid green;width: 80px;height: 30px;"></div>

    

    <div class="next" style="border: 1px solid red;height: 30px;">He loafed away the whole </div>

    <div class="next" style="border: 1px solid red;height: 30px;">He loafed away the whole </div>

    

    <div class="foo">Hello</div>

    <div class="foo">Hey</div>

    <p>I would like to say: </p>

    <p>I would like to say: </p>

    

  </body>

</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

链诸葛

真爱了。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值