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

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

本文关键字:不起作用 为什么 html 上的 preventDefault 附加      更新时间:2023-09-26

标题非常不言自明。我在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);