Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.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
.on()jquery不工作_Jquery_Ajax_Dom - Fatal编程技术网

.on()jquery不工作

.on()jquery不工作,jquery,ajax,dom,Jquery,Ajax,Dom,可能重复: 我知道.live()不推荐使用,但是.on()给我带来了一些错误。 当我动态生成圆顶时,它不起作用,它只在第一次单击时起作用。而与.live()相同的代码可以正常工作。我正在使用jQuery1.8 工作代码 $('.item').live('click', function(e) { alert('test'); // ajax call that regenerates .item element }); 此代码仅在第一次单击时有效: $('.item').on

可能重复:


我知道.live()不推荐使用,但是.on()给我带来了一些错误。 当我动态生成圆顶时,它不起作用,它只在第一次单击时起作用。而与.live()相同的代码可以正常工作。我正在使用jQuery1.8

工作代码

$('.item').live('click', function(e) {
   alert('test');
   // ajax call that regenerates .item element
});
此代码仅在第一次单击时有效:

$('.item').on('click', function(e) {
   alert('test');
   // ajax call that regenerates .item element
});

出什么问题了?

由于您的Ajax改变了dom,您需要在您的随叫随到中提供一个家长,如下所示:

$("#itemParent").on("click", ".item", function(event){
  alert('test');
});
检查一下
.on
的工作原理稍有不同:

$(document).on("click", ".item", function(event){
    alert('test');
    // ajax call that regenerates .item element
});

正如Kevin B提到的,使用文档作为委托上下文,或者更好的静态父对象:

$(document).on('click','.item', function(e) {
   alert('test');
   // ajax call that regenerates .item element
});

您没有提供上下文。.live的上下文是
文档
。这已经被问了很多次了。