简体   繁体   中英

jquery function works with live, not with on

trying to use the preferred on method call but the code is not working with on but does work with the live method.

Okay, I have a simple button element.

<button id="EditVal" name="EditVal" style="btn" value="Edit Debt">Edit Debt </button>

If I use the live method this code works:

$("#EditVal").live("click", function(e){
    alert('Edit this Val');
})

But this doesn't

$("#EditVal").on("click", function(e){
    alert('Edit this Val');
})

What am I doing wrong?

You're using on() like bind() , not like live() . To use it like live() , you should write:

$(document).on("click", "#EditVal", function(e) {
    alert('Edit this Val');
});

Note that, for performance reasons, it's preferred to call on() on a non-dynamic ancestor element instead of document , ie to use it like delegate() instead of live() .

Using on as you are attaches the event on page load. As you are dynamically loading the content, you need to use on as you would delegate by placing the handler on a parent element, and passing a filtering selector.

Try this:

$("#ParentOfEditVal").on("click", "#EditVal", function(e){
    alert('Edit this Val');
})

If your dynamically dropping a html element on the page then you need live. Here is why, on is set to work on EditVal if EditVal exsists on pageload. Since it does not I am assuming, the live function is needed as that can be bounded late after the initial page load. I think that was the original thought behind live in the first place. Any particular reason why you are using on instead of live?

The logic is that .on() binds the event to an object that is in the DOM. Then you give, as a parameter, the selector to find the child-element you want the trigger the event.

$("#parent_has_to_be_in_dom").on("click", "#myButton", function(event) {
    // should work like live
    alert("well hello");
});

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