开发者

Event delegation failing due to difference in targeted element between browsers

This is a simplified excerpt from the DOM:

<td>
    <button value="11" class="expand ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only" role="button" title="">
        <span class="ui-button-icon-primary ui-icon ui-icon-plus"></span>
        <span class="ui-button-text"></span>
    </button>
</td>

This is repeated for every row in the table (~500), and the table has an ID of 'eventTable'

Here's the button instantiation (jQueryUI):

$('.expand').each(function(){
    $(this).button({
        text: false,
        icons: {
            primary: "ui-icon-plus"
        }
    });
});

Here's a part of the event delegation on table #eventTable

$('#eventTable').click(function(e){
    if($(e.target).is('.expand'){
        // ...

Now, in Firefox 3.6.x, IE7,8, this works and steps into the if statement. In Safari and Chrome, however, e.target represents the first span instead of the surrounding 开发者_运维问答button.

Why is this happening? I can work past it, but I would love an explanation so I don't run into the same problem later in a different scenario. Why is Webkit right and Trident/Gecko wrong? What caused the difference?


Posting my comment as an answer.

If you're just wary not to get a ton of click handler references on your DOM, I'd suggest you use .delegate() instead. It "binds" only one handler onto a context, and checks if the event target matches a selector you provide, and fires off the handler if it does.

Something like

$('#eventTable').delegate('click', '.expand', function() {
    // click on the .expand element/s
});

should suffice.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜