开发者

What's the recommended way to create an HTML element and bind a listener to it using jQuery?

At the moment I achieve this using something like this:

var myElem = "<tr id='tr-1'><td>content</td></tr>";
$("#myTable").append(myElem);
$("#tr-1").click(function() {
  // blah blah
});

Traditionally, when I wasn't using jQuery, I used to do something like this:

var myElem = document.createElement(...);
var myTable = 开发者_Go百科document.getElementById("myTable");
myTable.appendChild(myElem);
myElem.onclick = function() {
  // blah blah
}

The thing is, in the second approach I already have a reference to myElem and I don't have to scan the DOM ($("#tr-1")) to find it, like the jQuery approach, and hence it should be much faster especially in big pages. Isn't there a better jQuery-ish way to accomplish this task?


You can shrink it down/speed it up a bit like this:

$("<tr id='tr-1'><td>content</td></tr>").click(function() {
 // blah blah
}).appendTo("#myTable");

This takes out the need to find the element, and also you're dealing with a document fragment until you actually call .appendTo(), making it much faster to do DOM operations.

There's also $(html, props) version since 1.4 that doesn't quite work for your example, but is even more terse in some situations that you may want to check out.


use live events. now when you add the element to the dom the live event gets added to the new element.

$(document).ready(function() {
  $("#tr-1").live("click", function() { 
    // blah blah 
  }); 
}


Just "cast" myElem into a jQuery object?

$(myElem).click(function() { ... });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜