我正在获取一个 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模板网!
在 Angular 2/Typescript 中使用 IScrollUse IScroll in Angular 2 / Typescript(在 Angular 2/Typescript 中使用 IScroll)
Anime.js 在 Ionic 3 项目中不起作用anime.js not working in Ionic 3 project(Anime.js 在 Ionic 3 项目中不起作用)
Ionic 3 - 使用异步数据更新 ObservableIonic 3 - Update Observable with Asynchronous Data(Ionic 3 - 使用异步数据更新 Observable)
Angular 2:在本地 .json 文件中找不到文件Angular 2: file not found on local .json file(Angular 2:在本地 .json 文件中找不到文件)
在 Ionic 2 中,如何创建使用 Ionic 组件的自定义指In Ionic 2, how do I create a custom directive that uses Ionic components?(在 Ionic 2 中,如何创建使用 Ionic 组件的自定义指令?)
将 ViewChild 用于动态元素 - Angular 2 &离子2Use ViewChild for dynamic elements - Angular 2 amp; ionic 2(将 ViewChild 用于动态元素 - Angular 2 amp;离子2)