本文介紹了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();
});
- 首先,選擇您的共同祖先元素(本例中為
#title-items
).如果你想處理 alla
元素,你也可以在這里使用document
. - 傳遞事件類型(
on
),然后子選擇器(a
),然后是事件的回調函數.
- First, select your common ancestor element (
#title-items
in this example). You can usedocument
here too if you want to handle alla
elements. - 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.
這篇關于jQuery .on() 方法看不到新元素的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!