jQuery prepend()和prependTo()示例

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

例如,

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

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

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

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

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

结果

以上两种方法都执行相同的任务,但是使用不同的语法, prepend()prependTo()之后的新内容将变为
这确实是多功能工具。 对于要在其上使用滑块的任何网站,这都是这样做的方法。 如果您查看任何大型网站,例如www.o2.co.uk/之类的网站,或电影网站,您很可能会看到一个正在使用的网站。 这是一种使图像旋转看起来很灵巧并吸引观看者眼球的好方法。 它为您的网站增加了不同的维度,使其真正脱颖而出。

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

<div class="box">
   <div class='newbox'>I'm new box by prepend</div>
   I'm a big box 2
</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 prepend() and prependTo example</h1>

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

翻译自: https://mkyong.com/jquery/jquery-prepend-and-prependto-example/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值