开发者

Modifying Element with jQuery using Event

I have a table set up such that each row has a checkbox as the first item in the row (think Gmail's inbox). The <tr> of that row has a hover and click event handler bound to it.

What I want to happen is, when the user clicks on the checkbox, the checkbox becomes checked and that's all. When the user clicks anywhere else in the row, it should do something else. I am trying to achieve this by looking at the event.target of the event being passed and seeing if that's a checkbox or not. However, with my current implementation, when the user clicks on the checkbox, nothing happens and when they click anywhere else in the row, it behaves how I expect.

What am I doing wrong with regards to the checkbox?

Here is my code:

$('.navTable > tbody > tr').hover(function() {

if (!$(this).children('td').hasClass('spacer') && !$(this).children('th').length > 0)
    $(this).css({background : "#EFEFEF", border : "1px solid #CCC"});
},function() {
    $(this).css({background : "", border : ""});
}).click(function(e) {
    console.log(e);
    if(e.target.attributes[0].nodeValue == "checkbox") {
        // Check the checkbox
        $("#"+e.target.id).attr('checked', 'checked');
    } else {
        // Do somethi开发者_如何学JAVAng else
    }
    return false;
});

Thank you for any help you might provide.


Why don't you make separate click handlers for the checkbox and elsewhere in the row:

$('.navTable > tbody > tr input').click(function(e) {
    // do whatever you want here
    e.stopPropagation();
    alert("click checkbox");
})

$('.navTable tr').click(function(e) {
    // click in a row, that's not in the checkbox
    alert("click row");
})

Example here: http://jsfiddle.net/jfriend00/KEu3a/.


try

$('.navTable tr').hover(function() { 
    if (!$(this).children('td').hasClass('spacer') && !$(this).children('th').length > 0) 
    $(this).css({background : "#EFEFEF", border : "1px solid #CCC"}); 
    },function() { 
            $(this).css({background : "", border : ""}); 
    }).closest('table')
        .delegate(':checkbox', 'change',function() { 
            var $checkbox = $(this),
            $td = $checkbox.closest('td'),
            $tr = $td.closest('tr');

        //If its not checked do something else.
        if($checkbox.not(':checked')) { 
      // Do something else 
    } 
    return false; 
}); 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜