简体   繁体   中英

How to register click event for ajax loaded content

Here is the html i have

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

Here is my 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

$('#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. 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.

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.

I can suggest small solution for that. This is not best practise, but will solve your problem:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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