Pie*_*ier -2 javascript ajax jquery
这件事让我疯了.
所以我通过AJAX加载一些简单的HTML,一旦它加载到DOM上我就这样做了.
$('#wrap a.link').click(function(e) {
e.preventDefault();
alert("asdasdad");
});
Run Code Online (Sandbox Code Playgroud)
它只是不会阻止链接导航到href属性中的url.
我的语法似乎正确,我确保元素在DOM中,并且函数找到了a.link元素.
$("#wrap a.link").each(function(key, value) {
console.log("found a link"); // this shows up in the console
});
Run Code Online (Sandbox Code Playgroud)
我也试过使用off(),stopImmediatePropagation()以防万一其他事件可能会干扰,但没有.我也尝试each()使用相同的结果在循环内绑定事件.
什么可能导致这种行为?
将事件绑定到正文以获取动态元素:
$('body').on('click','#wrap a.link',function(e) {
e.preventDefault()
});
Run Code Online (Sandbox Code Playgroud)
使用事件委托:
$(document).on('click', '#wrap a.link', function(e) {
e.preventDefault();
alert("asdasdad");
});
Run Code Online (Sandbox Code Playgroud)
警告: 保持您的ID唯一.