开发者

Performance of delegate()

I've been using $("body").delegate(".selector", "click", function() { ... }); for a while now, and I was wondering: If I delegate the click event to a containing element closer to the actual element, for example a table full of buttons, would this be faster than delegating the same event to body, seeing开发者_运维技巧 as the event doesn't have to bubble as far?

Basic HTML example:

<html>
    <body>
        <table>
            <tr>
                <td>
                    <input type="button" value="Delegated element">
                </td>
            </tr>
            <!-- More, identical rows -->
        </table>
    </body>
</html>

First example, using body:

$('body').delegate('input[type="button"]', 'click', function() {
    // Do things
});

Second example, using table:

$('table').delegate('input[type="button"]', 'click', function() {
    // Do things
});

Which of the two examples above is faster, and if one is faster than the other, why?


If I delegate the click event to a containing element closer to the actual element, for example a table full of buttons, would this be faster than delegating the same event to body, seeing as the event doesn't have to bubble as far?

Yes, it would be faster and precisely for the reason you suggest. I think this is a helpful article and fairly relevant to your question.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜