开发者

jQuery detect which element a onClick occurs to

I'm attempting to activate table row checkbox when the user clicks within a table row. Each row has a checkbox.

I have the following code which works fine as a standard version.

$('.scrol开发者_StackOverflow社区lTable tr').click(function(event) {
    if(event.target.type !== 'checkbox') {
        $(':checkbox', this).trigger('click');
    }
});

The data in the table I'm attempting to add this to has various types i.e. there are images which create popups, links which create tooltips and links which redirect to another page. The problem I'm having is that in clicking a link, image etc the corresponding checkbox is ticked.

Any ideas?


Propagation is the issue here. When you click an image or link, that event bubbles up through the ancestors and fires the click handler when it reaches the <tr> element. event.target will refer to the original clicked element. You should be more specific about the "type"s you allow or disallow. For example:

$('.scrollTable tr').click(function(event) {
    if(event.target.tagName == 'TD') {
        $(':checkbox', this).trigger('click');
    }
});

Example disallowing <a>, <img> and <input> using an object map:

$('.scrollTable tr').click(function(event) {
    var disallow = { "A":1, "IMG":1, "INPUT":1 }; 
    if(!disallow[event.target.tagName]) {
        $(':checkbox', this).trigger('click');
    }
});


you probably need to look in to event.stopPropagation - this should stop the event bubbling up to the checkbox


this should work:

$('.scrollTable tr').click(function(event) {
    var $this = $( event.currentTarget );

    if( $this.is( 'tr' ) )
    {
        $(':checkbox', this).trigger('click');
    }
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜