繁体   English   中英

附加的html上的preventDefault()不起作用。 为什么?

[英]preventDefault( ) on appended html does not work. why?

标题很容易解释。 我正在通过AJAX调用将HTML附加到我的文档中,并且当您单击由此函数生成的<a>标记时,我想阻止默认事件。 这是我的代码:

$.ajax({
type: 'GET',
url: "/api/search/info/" +id,
accepts: 'application/json'
}).then(function(data, status, xhr) {
  $(".book-results #results").append("<a class='bookitem' href='b"+data.value+"'>Add Book</a>");
}, showErr);

在相同的javascript文件中(但不在AJAX函数中),我有以下侦听器:

$(".bookitem").click(function(event) {
  event.preventDefault();
  console.log("HELLO");
});

当我触发ajax事件时,将填充.book-results #results ,但是当我单击<a>标记时,将触发默认事件。 有没有办法让听众工作? 如果是这样,怎么办?

您不能在尝试附加侦听器的元素存在之前应用事件侦听器。 因此, $(".bookitem").click(function(event) {...}); 只会将元素与当时存在的bookitem类绑定。

如果要动态添加元素,则需要在创建元素后将事件处理程序附加到这些元素上,或者最好使用委托。

对于委托,您将事件处理程序附加到父元素,例如:

$(".book-results #results").on("click",".bookitem", function(event) {
    // your handler goes here.
});

对于jQuery 1.7或更高版本,请使用.on() ...

$(document).on("click", ".bookitem", function(event){
  event.preventDefault();
  console.log("HELLO");
});

否则使用.delegate() ...

$(body).delegate(".bookitem", "click", function(event){
  event.preventDefault();
  console.log("HELLO");
});

尝试:

$(".book-results").on('click','a',function(event) {
  event.preventDefault();
  console.log("HELLO");
});

创建元素后必须附加事件...

$.ajax({
   type: 'GET',
   url: "/api/search/info/" +id,
   accepts: 'application/json'
}).then(function(data, status, xhr) {
    $(".book-results #results").append("<a class='bookitem' href='b"+data.value+"'>Add Book</a>");
    $(".bookitem").click(function(event) {
       event.preventDefault();
       console.log("HELLO");
    });
}, showErr);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM