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(''));
        }
    );
}

我正在为 a 元素绑定点击事件,如下所示:

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

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

旧的 a 元素显示警报,但新元素跟随 URL.事件处理程序不适用于新的.我该如何解决这个问题?

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

推荐答案

您没有使用正确的代码来获得 live 功能.

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).如果你想处理 all a 元素,你也可以在这里使用 document.
  2. 传递事件类型(on),然后子选择器(a),然后是事件的回调函数.
  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.

现在,当 click 事件冒泡到 #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.

相关文章