我正在获取一个 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();
});
#title-items
).如果你想处理 all a
元素,你也可以在这里使用 document
.on
),然后子选择器(a
),然后是事件的回调函数.#title-items
in this example). You can use document
here too if you want to handle all a
elements.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.
这篇关于jQuery .on() 方法看不到新元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!