单击时触发事件,复选框+标签除外

时间:2012-09-14 21:36:22

标签: javascript jquery

我有一个表行,单击时会触发一个事件。在行内有(未显示)复选框+其样式标签。

我想要的是防止(我想:不是或.not()但是无法弄明白)执行如果单击复选框/标签。

HTML:

<center>
<table>
    <tr class='pend'>
        <td><input type="checkbox" id="bb"/> <label for="bb">X</label></td>
        <td>&nbsp;</td>
        <td>some text</td>
    </tr>
</table>
</center>

CSS:

center {
margin-top:20px;
}

input[type=checkbox] + label {
    width:10px;
    height:10px;
    background-color:red;
}

input[type=checkbox] {
    display:none;
}

table tr {
height:40px;
    background-color:gray;
}

table td {
padding:5px;
}

JS:

$('.pend').on('click',function(){
    $(this).append('text');
    return false;
})

JSFIDDLE:http://jsfiddle.net/ySuGB/2/

4 个答案:

答案 0 :(得分:2)

您需要在点击复选框/标签时阻止事件冒泡。

见下文,

//                     V-- Is the TD containing the checkbox and the label.
$('.pend :checkbox').parent().on('click', function(event) {
    event.stopPropagation()
});

DEMO: http://jsfiddle.net/ySuGB/12/

答案 1 :(得分:1)

e.stopPropagation()就是您所需要的。

http://jsfiddle.net/jNDYJ/

$('.pend input:checkbox').add('.pend label[for=bb]').click(function(e){
    e.stopPropagation();
});

答案 2 :(得分:0)

您可以检查事件目标是否为标签(等):

$('.pend').on('click',function(e){
  if(e.target.tagName=='LABEL')
    return false;
  $(this).append('text');
  return false;
})​

http://jsfiddle.net/ySuGB/9/

答案 3 :(得分:0)

$('.pend').on('click',function(){
    var $this = $(this);
    $this.off('click');
    $this.find('td:eq(2)').append('text');
})​
相关问题