当目标与选择器不匹配时触发jQuery事件

时间:2012-02-23 20:50:27

标签: jquery events

我有以下标记:

<table>
    <tbody>
        <tr>
            <td>
                <a href="javascript:void(0)" class=expand>click me</a>
                <span>some other content</span>
            </td>
            <td>
                click me too
            </td>
        </tr>
    </tbody>
</table>

我正在将行的点击处理程序附加到表中:

$('table').on('click', 'tr :not(".expand")', function(evt) {
    if (! $(evt.target).is(selector)) {
        console.log('event is firing even though target doesnt match the selector!!!');
    } else {
        console.log('event is firing as expected');
    }
});

var selector = $('table').data('events').click[0].selector;

JSFiddle

我希望事件仅在源自与tr :not(".expand")选择器匹配的元素(条件的else部分)时触发,但事件无论如何都会触发。

如何将回调绑定到<table>元素处的事件,以便只有当它不是被点击的.expand元素时才会触发?

澄清:如果用户点击<span>some other content</span>

,仍应执行事件处理程序

3 个答案:

答案 0 :(得分:2)

我相信你想要这个:

$('table').on('click', 'tr td:not(:has(".expand"))', function(evt) {
    console.log("Event only fires when clicking something that doesn't contain an expando");
});

var selector = $('table').data('events').click[0].selector;

jsFiddle

答案 1 :(得分:1)

尝试使用.is(...)event.target

$('table').on('click', 'tr :not(".expand")', function(evt) {
    if ($(evt.target).is('tr :not(".expand")')) {
        alert('clicked it!');
    }
    else {
        alert('not')
    }
});​

小提琴:http://jsfiddle.net/maniator/h9yh7/

答案 2 :(得分:0)

如果你想处理.expand,而不是触发行点击,

$('table').on('click', '.expand', function(evt) {
    evt.stopPropagation(); 
    console.log('expand clicked!');
});

jQuery.stopPropagation()