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?
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?
Share Improve this question asked Jan 19, 2012 at 14:43 Michael BWMichael BW 1,0703 gold badges13 silver badges26 bronze badges 1- 1 What is the jQuery version you are using? Make sure it is 1.7+. – ShankarSangoli Commented Jan 19, 2012 at 14:45
4 Answers
Reset to default 9You'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
, i.e. 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");
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744305190a4567694.html
评论列表(0条)