如何为 ajax 加载的内容注册单击事件

How to register click event for ajax loaded content

本文关键字:注册 单击 事件 ajax 加载      更新时间:2023-09-26

这是我拥有的html

<input type="text" name="post[price]" id="productUpdate" class="test" disabled />
<div class="abs-locator" id="eventDrive"></div>

这是我的 CSS

.abs-locator{
  width: 17.8%;
  position: absolute;
  margin-top: -29px;
  margin-left: 150px;
  height: 27px;
}
单击

隐藏输入框时,我需要执行单击事件

这是我的 js

$('#eventDrive').on('click', function() {
    alert('test');
});

但在这里什么也没发生。为什么会发生这种情况以及如何解决它

要在 Ajax 加载的内容上有一个点击事件,你必须在容器上注册该事件。我会做这样的事情:

$(document).on('click', '#eventDrive', function() {
    alert('test');
});
这样,单击

侦听器将在整个文档中注册,并且每次单击时,它都会检查您是否单击了 #eventDrive,即使在您注册侦听器时该元素不存在也是如此。

你需要使用类似的东西:

$(document).on('click', '#eventDrive', function() {
    alert('test');
});

禁用的元素不会触发鼠标事件。大多数浏览器会将源自禁用元素的事件传播到 DOM 树上,因此可以将事件处理程序放置在容器元素上。

我可以为此提出小解决方案。这不是最佳做法,但可以解决您的问题:

.HTML:

<div style="display:inline-block; position:relative;">
    <input id="productUpdate" name="post[price]" type="text" disabled />
    <div class="inputOverflow" style="position:absolute; left:0; right:0; top:0; bottom:0;"></div>
</div>

j查询:

$(".inputOverflow").click(function (evt) {
    $(this).hide().prev("input[disabled]").prop("disabled", false).focus();
});​