开发者

JavaScript use hundreds of closure or one function call

开发者 https://www.devze.com 2023-03-16 21:33 出处:网络
I have a data web page with possibly few thousands开发者_开发技巧 TDs in it.Some of the TD\'s will need a bound onclick event that uses the contents, or part of the contents of the TD.

I have a data web page with possibly few thousands开发者_开发技巧 TDs in it. Some of the TD's will need a bound onclick event that uses the contents, or part of the contents of the TD.

I'm using jQuery to add the onclick closure like this:

$(".date").click(function() {
    var d = this.html();
    doSomething(this, d, otherparams);
}

Is this efficient? It seems that my page would contain few hundreds, or thousands of almost identical closures. Would it be better to put this doSomething call somewhere else.


Infact, this is very inefficient. Even more because you can so easily workaround it using event delegation. Doing that, will use only one event handler method instead of "thousands".

$('table').delegate('td.date', 'click', function( event ) {
    var d = $(this).html();
    doSomething(this, d, otherparams);
});

You need to call this construct only once (outside of any loop). It'll bind an click event handler to all tables in the above example (you should be more precise using an id for instance). Since most browser events do "bubble" up the DOM tree, any click which happens in a <td> element will finally reach the <table> and is processed there.

Ref.: .delegate()

0

精彩评论

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

关注公众号