Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/435.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery click()事件未在AJAX加载的HTML元素上触发_Javascript_Jquery_Ajax - Fatal编程技术网

Javascript jQuery click()事件未在AJAX加载的HTML元素上触发

Javascript jQuery click()事件未在AJAX加载的HTML元素上触发,javascript,jquery,ajax,Javascript,Jquery,Ajax,这个主题很好地描述了我的问题,我假设它不会以这种方式工作,有没有办法让它工作?(解决办法) 以下是通过AJAX加载的代码: <div> <div id="s0frame" class="sframe"></div> <div id="s1frame" class="sframe"></div> <div id="s2frame" class="sframe"></div> <div id="s3frame"

这个主题很好地描述了我的问题,我假设它不会以这种方式工作,有没有办法让它工作?(解决办法)

以下是通过AJAX加载的代码:

<div>
<div id="s0frame" class="sframe"></div>
<div id="s1frame" class="sframe"></div>
<div id="s2frame" class="sframe"></div>
<div id="s3frame" class="sframe"></div>
<div id="s4frame" class="sframe"></div>
<div id="s5frame" class="sframe"></div>
<div id="chatframe" class="chat alpha60"></div>
</div>

除非在将该标记加载到页面后调用该.bind()函数,否则需要使用另一个函数,如.live(),或者最好使用最新版本的jQuery、.on(),因为.bind()只针对运行时已存在的DOM元素,而.live()和.on()则是为您提供不同的作用域选项,以跟踪添加到页面的元素。

执行此操作

 $(document).on("click",".sframe",function(e){
 var seat_number = this.id.match(/\d/g);
 alert(seat_number); 
 });

编辑:


从jQuery 1.7开始,.live()方法已被弃用。使用.on()附加事件处理程序。jQuery旧版本的用户应该使用.delegate()。

您必须将事件处理程序重新附加到动态添加到DOM中的元素
.live
方法曾被广泛使用,但现在已被弃用。在jQuery版本1.7+中,您可以使用

使用委托

$(document).delegate(".sframe","click",function(e){

});

.live()
从jQuery 1.7开始就不推荐使用,因此请使用它的替代品
.on()
更新版本谢谢你的作品,因为你先回答了,我会选择你!当我尝试.on()而不是.live()时,它不会启动。(编辑:这是因为我使用的是1.7吗?)由于使用了
live()
,所以被否决。它已被弃用,不应再推广它的使用(甚至在
on()
之前,建议使用
delegate()
而不是
live()
)。如果答案是固定的,我将删除我的否决票。@AngelWorkz谢谢,我已经删除了否决票(
on()
变体仍然不正确,请参见3nigma的答案)。谢谢您的解释!这非常有帮助。谢谢@3nigma。第一种方法非常有效。
 $(document).delegate(".sframe","click",function(e){
 var seat_number = this.id.match(/\d/g);
 alert(seat_number); 

 });
$(document).on("click",".sframe",function(e){

});
$(document).delegate(".sframe","click",function(e){

});
$(document).on('click','sframe', function() { 
    var seat_number = this.id.match(/\d/g);
    alert(seat_number); 
});