在jquery中被if / else语句困惑

时间:2014-09-21 16:43:35

标签: jquery

我正在尝试编写一些代码,点击按钮后,您可以从团队成员列表中选择一名队长。单击按钮后,可能的团队成员(排列在表格中)会更改颜色,然后如果单击其中一个,则会将其指定为新的队长。我想要它,以便如果您点击屏幕上的任何其他位置,团队成员将恢复其正常颜色,页面将恢复正常。

Here是我尝试的小提琴。如你所见,它不起作用。

我的HTML是:

<table>
    <tr>
        <td class="name">John Smith</td><td class="captain"></td>
    </tr>
    <tr>
        <td class="name">Smith Johnson</td><td class="captain"></td>
    </tr>
    <tr>
        <td class="name">Joth Smithson</td><td class="captain"></td>
    </tr>
</table>
<div id="button">C</div>

我的js是:

$('#button').click(function() {
    var people = $('table tr')
    people.css('background-color','red');
    people.find('td.captain').html('');
    $('html').click(function(event) {
        var target = $(event.target);
        if($('table tr').has(target).length) {
            var newcaptain = $('table tr').has(target);
            newcaptain.find('td.captain').html('C');
            people.css('background-color','');
            $('html').off('click');
        } else {
            people.css('background-color','');
            $('html').off('click');
        }
    });
});

令我感到困惑的是,如果我从else子句中删除语句,if部分就像我想要的那样工作。这怎么可能?

2 个答案:

答案 0 :(得分:0)

这是因为event bubbling。在#button单击方法完成后,浏览器将在DOM层次结构中向上运行,直到它到达根元素,查找其他click个事件。因为您向html标记添加了单击事件,所以浏览器会找到并执行它。当你没有点击tr(你点击了按钮)时,else语句会运行并撤消你的css。

如果您在$('html).click之前添加提醒,则很容易看到:

$('#button').click(function() {
    var people = $('table tr')
    people.css('background-color','red');
    people.find('td.captain').html('');
    alert('button click');
    $('html').click(function(event) {
        var target = $(event.target);
        if($('table tr').has(target).length) {
            var newcaptain = $('table tr').has(target);
            newcaptain.find('td.captain').html('C');
            people.css('background-color','');
            $('html').off('click');
        } else {
            people.css('background-color','');
            $('html').off('click');
        }
    });
});

你会看到你的按钮代码有效,但当你关闭警报时它会立即恢复。

因此,您需要在按钮单击后停止发生事件冒泡。最简单的方法是返回false,或者调用event.stopPropogation();告诉浏览器停止冒泡:

$('#button').click(function(event) {
    event.stopPropagation();
    var people = $('table tr')
    people.css('background-color','red');
    people.find('td.captain').html('');
    $('html').click(function(event) {
        var target = $(event.target);
        if($('table tr').has(target).length) {
            var newcaptain = $('table tr').has(target);
            newcaptain.find('td.captain').html('C');
            people.css('background-color','');
            $('html').off('click');
        } else {
            people.css('background-color','');
            $('html').off('click');
        }
    });
});

我更新了你的小提琴,添加:http://jsfiddle.net/jsfnvwvz/7/

答案 1 :(得分:0)

当您单击按钮事件发送给它时,还会发送到所有父图层(正文,html,文档)。

要防止这种情况使用event.stopPropagation()

$('#button').click(function(event) {
    event.stopPropagation();
    ...
}

fiddle