Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 views
in Technique[技术] by (71.8m points)

adding jQuery click events to dynamically added content

I have a table with multiple rows and columns populated by php and mySQL. For some of the td's I'm adding jQuery click-events in the document.ready function to let the user change the content.

But I also have an option for adding rows to the table and populating them manually. But since the rows I'm adding aren't there on the document ready, they won't get the click event handler appended, and so I'm not able to click them to get input boxes.

<table>
  <tr>
    <td class="clickable">Some info</td>
    <td class="clickable">Some more info</td>
    <td>Unchangable info</td>
  </tr>
  ... more similar rows ...
</table>

and then the jQuery

$("tr.clickable").click(function() {
   //add input fields
}

$("span#addNewRow").click(function() {
   $("table").append('<tr><td class="clickable"></td> ... </tr>')
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You want to use live events, which were introduced in 1.3.

$("tr.clickable").live("click", function() {
   //add input fields
});

$("span#addNewRow").live("click", function() {
   $("table").append('<tr><td class="clickable"></td> ... </tr>')
});

UPDATE: Note that as of jQuery 1.7, live() is deprecated. Use on() instead. And in some cases, delegate() may be a better choice. See the comments below.

Example of how to use .on():

$("table").on("click", "tr.clickable", function() {
   //add input fields
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...