简体   繁体   English

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

[英]How to register click event for ajax loaded content

Here is the html i have 这是我的html

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

Here is my css 这是我的CSS

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

I need to perform click event when hidden input box is clicked 单击隐藏的输入框时,我需要执行单击事件

Here is my js 这是我的js

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

But here nothing happens. 但这里没有任何反应。 Why this is happening and how to resolve it 为什么会这样,以及如何解决它

To have a click event on Ajax loaded content you have to register the event on the container. 要在Ajax加载的内容上有一个click事件,你必须在容器上注册事件。 I would do something like this: 我会做这样的事情:

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

This way the click listener will be registered on the whole document, and every time you click it will check if you clicked on the #eventDrive, even if that element didn't exist at the time when you registered the listener. 这样点击监听器将在整个文档中注册,每次单击它都将检查您是否单击了#eventDrive,即使您在注册监听器时该元素不存在。

You need to use something like : 你需要使用类似的东西:

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

Disabled elements don't fire mouse events. 禁用的元素不会触发鼠标事件。 Most browsers will propagate an event originating from the disabled element up the DOM tree, so event handlers could be placed on container elements. 大多数浏览器会将源自禁用元素的事件传播到DOM树上,因此事件处理程序可以放在容器元素上。

I can suggest small solution for that. 我可以为此建议小解决方案。 This is not best practise, but will solve your problem: 这不是最佳做法,但会解决您的问题:

HTML: 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>

jQuery: jQuery的:

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

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

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