简体   繁体   中英

jQuery .live('click') seems to only bind to the first element

So I have a bunch of buttons on a page, interspersed with other HTML, that look like this:

<input class="add_new_task" type="submit" value="Add New Task">
<input class="add_new_task" type="submit" value="Add New Task">
<input class="add_new_task" type="submit" value="Add New Task">

And then I have my selector as follows:

$JQ('.add_new_task').live('click', function(){
    //do some stuff
});

However, the live('click') only seems to bind to the first element, and so nothing will happen with the 2nd, 3rd etc. elements. Any suggestions as to what I'm doing

EDIT:

Turns out I was being stupid - I added some error checking to not allow submission if a text box was empty - but I was targetting the text box (stupidly) by id, and that in turn was selecting the first textbox with that ID - which indeed was empty. Changed to a class based selection system for these now - thanks for all the answers though!

Found this on the jQuery API site

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.

Try using the .on() method other than that it all looks fine to me

Use .on() if this is jQuery 1.7+

http://api.jquery.com/on/

EDIT: Also, depending on what you are doing, .on() may not be necessary. Try .click()...

$JQ('.add_new_task').click(function(){
  //do some stuff
});

first of all you should be using .on , because on replaces all event binding as of 1.7, but you might be using a lower version off course. When you are using live, you want to be using event delegation, this means you have to bind to a parent object which will then handle specific propagated events from (specific) child elements.

wrap your input fields in a div like this

<div id="tasks">
    <input class="add_new_task" type="submit" value="Add New Task">
    <input class="add_new_task" type="submit" value="Add New Task">
    <input class="add_new_task" type="submit" value="Add New Task">
</div>

with .live this should work:

$JQ('#tasks').live('click', function(){
    //do some stuff
});

Better off course would be to use .on like this ( same html )

$("#tasks").on("click", ".add_new_task", function(event){
    //do some stuff
});

http://api.jquery.com/on/

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