jquery bind方法与on方法 区别

1.参数不同

.bind(events,[eventData],handler)
.on(events,[selector],[data],handler)
.on的selector参数是筛选出调用.on方法的dom元素的指定子元素,如:
$(‘ul’).on(‘click’, ‘li.child1’, function(){console.log(‘click’);})
就是筛选出ul下的类名为child1的li给其绑定click事件;

2. 给动态添加的元素绑定指定事件用on方法
<div class="content1">
  <div class="child" style="background: khaki">content1原有</div>
</div>
<button>content1增加一个child元素</button>
<script>
  $(function () {
    $('button').click(function () {
      //动态添加新元素
      $('.content1').append('<div class="child" style="background:darkseagreen">content1新增</div>')
    })
    $(".content1 .child").bind("click",function () {
      console.log('bind方法',$(this).text())
    })
    $(".content1").on("click",".child",function () {
      console.log('on方法',$(this).text())
    })
  })
</script>
3. on方法事件委托
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>
<script>
  $(function () {
    $('ul').on('click','li',function () {
      $(this).css('background','lightsalmon').siblings().css('background','#fff')
      console.log($(this).index())
    })
  })
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值