jQuery append()和appendTo()示例

jQuery append()appendTo()方法都执行相同的任务,在匹配元素的内容之后添加文本或html内容。 主要区别在于语法。

例如,

<div class="box">I'm a big box</div>
<div class="box">I'm a big box 2</div>

1. $('selector')。append('new text');

$('.box').append("<div class='newbox'>I'm new box by prepend</div>");

2. $('new text')。appendTo('selector');

$("<div class='newbox'>I'm new box by appendTo</div>").appendTo('.box');

结果

上面的两个方法都执行相同的任务,但是使用不同的语法, append()appendTo()之后的新内容将变为

<div class="box">
   I'm a big box
   <div class='newbox'>I'm new box by prepend</div>
</div>

<div class="box">
   I'm a big box 2
   <div class='newbox'>I'm new box by prepend</div>
</div>

自己尝试

<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<style type="text/css">
	.box{
		padding:8px;
		border:1px solid blue;
		margin-bottom:8px;
		width:300px;
		height:100px;
	}
	.newbox{
		padding:8px;
		border:1px solid red;
		margin-bottom:8px;
		width:200px;
		height:50px;
	}
</style>

</head>
<body>
  <h1>jQuery append() and appendTo example</h1>

  <div class="box">I'm a big box</div>
  
  <div class="box">I'm a big box 2</div>
  
  <p>
  <button id="append">append()</button>
  <button id="appendTo">appendTo()</button>
  <button id="reset">reset</button>
  </p>
  
<script type="text/javascript">
	
    $("#append").click(function () {
		
	  $('.box').append("<div class='newbox'>I'm new box by append</div>");
	  
    });
	
	$("#appendTo").click(function () {
		
	  $("<div class='newbox'>I'm new box by appendTo</div>").appendTo('.box');
	  
    });
	
	$("#reset").click(function () {
	  location.reload();
    });
	
</script>
</body>
</html>

翻译自: https://mkyong.com/jquery/jquery-append-and-appendto-example/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值