jQuery .on()方法看不到新的元素 [英] jQuery .on() method doesn't see new elements

查看:114
本文介绍了jQuery .on()方法看不到新的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个JSON元素,并从其项目构建一个列表,如下所示:

I'm getting a JSON element and building a list from its items like this:

getTitles: function(data) {
    data = data || {};
    var list = [];

    $.getJSON(
        '/titles',
        data,
        function(data) {
            $.each(data.data, function(key, val) {
                list.push(
                    '<li><a href="'+ val.href +'">'+ val.title +'</a><span class="count">'+ val.count +'</span></li>'
                )
            });

            $('#title-items').html(list.join(''));
        }
    );
}

而且我绑定了 / code>这样的元素:

And I'm binding click event for a elements like this:

$('a').on('click', function(e) {
    alert('clicked');
    e.preventDefault();
});

旧元素显示警报,但新元素遵循URL。事件处理程序不适用于新的。如何解决这个问题?

Old a elements shows alert but new ones follow URL. Event handler doesn't work for new ones. How can I solve this?

推荐答案

您没有使用正确的代码来获得

You are not using the correct code to get live functionality.

$('#title-items').on('click', 'a', function(e) {
    alert('clicked');
    e.preventDefault();
});




  1. 首先,选择您的共同祖先元素( #title-items )。如果你想处理所有 元素,你也可以使用 document li>
  2. 传递事件类型(上),然后选择子选择器( / code>),然后是事件的回调函数。

  1. First, select your common ancestor element (#title-items in this example). You can use document here too if you want to handle all a elements.
  2. Pass the event type (on), then the sub selector (a), and then the callback function for the event.

现在,当 事件会触发#title-items ,它会检查元素是否为 a 元素,如果是,则触发回调。

Now, when click events bubble up to #title-items, it will check to see if the element is an a element, and if so, fire the callback.

这篇关于jQuery .on()方法看不到新的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆