Jquery对未来的元素不起作用?

Sha*_*aun 6 jquery future

我有点击功能......

$('.rx').children().on('click',function(){alert('got here');});
Run Code Online (Sandbox Code Playgroud)

我的div(页面上有50个div)......

<div class="rx"><div id="'.$data_string.'" class="'.$button_image_class.'"><a  href="#" ></a></div></div>
Run Code Online (Sandbox Code Playgroud)

(每个都是一个css sprite图像按钮,它将id中的$ data_string发送到一个函数"process_me".我已经用一个警告替换了对process_me的调用('got here');对于这个问题.FYI $ button_image_class是可变的,因为根据会员的帐户加载特定图像)

这一切都很美妙,直到我使用分页加载更多的上述div(另外50个,完全相同的bar $ data_string,这在所有div中都是不同的).

前50个div中的精灵图像按钮链接工作方式 - 单击它们提示"到达此处".但是,新加载的div集中的链接不起作用.

我首先猜到这是因为DOM没有拿起新的元素,但是.on('click',function()...应该会选择未来的元素.所以现在我认为它是

$('.rx').children().on('click',function(){alert('got here');});
Run Code Online (Sandbox Code Playgroud)

我做错了.

有什么东西伸出来吗?

mek*_*all 8

不,.on只会绑定到现有元素,除非您使用委托事件.

选项1

绑定到click事件以获取回调中新添加的元素(在将元素添加到DOM之后):

$.ajax({
    ...
}).done(function(){
    $('.rx').children().on('click', function() { 
        alert('got here');
    });
});
Run Code Online (Sandbox Code Playgroud)

选项#2

使用绑定到容器的委托事件:

$(document).on('click', '.rx > *', function() { 
    alert('got here');
});
Run Code Online (Sandbox Code Playgroud)

注意:您可能希望将选择器中的星号替换为与子项匹配的实际元素类型或类.尽可能避免在选择器中使用星号.上述的另一个改进是使用更接近.rx而不是直接绑定的父级document