对于动态加载内容 (包括 Ajax 请求内容) 绑定点击事件

1.问题展现

首先看看如下代码执行:

<html>
<head>
<meta charset="utf-8">
<title>文档标题</title>
</head>
<body>
    <div id="the_div">
    </div>
    <button id="btn">test</button>
  <script src="https://cdn.staticfile.org/jquery/2.2.4/jquery.min.js"></script>
  <script>
  $('#btn').click(function(){
    $('#the_div').append('<button>new button</button>');
})

$('#the_div button').click(function(){
    alert('clicked');
})
  </script>
</body>
</html>

初始时会监听#btn即test按钮,以及#the_div button即div中的所有按钮的click事件。当点击test按钮后div内会动态添加new button按钮,而我们期望点击new button按钮后,会弹出一个alert,但事实上这么做是不会触发alert的。

2.问题分析

.click()实际上是.on( "click", handler )的简化,而$( selector ).on( events, handler )只会对当前已经存在,且满足selector条件的元素绑定events,也就是说,这个绑定只针对于当前存在的元素,而在其之后加入到DOM中的元素,即使满足selector条件,也不会绑定对应的events

3.解决方案

实际上jQuery也有专门的方法解决这个需求,即[.live()],$( selector ).live( events, handler )会对所有当前和未来满足selector条件的元素绑定对应的events

但从jQuery 1.9开始,.live()就被移除了。

.live()的API文档中,官方就给出了替代.live()的方法,即目前最常用的方法:$( document ).on( events, selector, data, handler );

$( "a.offsite" ).live( "click", function() {
  alert( "Goodbye!" ); // jQuery 1.3+
});
$( document ).on( "click", "a.offsite", function() {
  alert( "Goodbye!" );  // jQuery 1.7+
});

对于上述例子的解决方案:

<html>
<head>
<meta charset="utf-8">
<title>文档标题</title>
</head>
<body>
    <div id="the_div">
</div>
<button id="btn">test</button>
  <script src="https://cdn.staticfile.org/jquery/2.2.4/jquery.min.js"></script>
  <script>
  $('#btn').click(function(){
    $('#the_div').append('<button>new button</button>');
})
//解决方案
$('body').on('click','#the_div button',function(){
    alert('clicked');
})
  </script>
</body>
</html>

原文:https://www.polarxiong.com/archives/jQuery...

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!