在jQuery中检测背景点击

Sen*_*ful 5 jquery mouseclick-event

说我有以下HTML:

<div>
  <span>span text</span> div text <span>some more text</span>
</div>
Run Code Online (Sandbox Code Playgroud)

我想这样做,以便当我单击span时将触发一些事件(例如,使文本变为粗体),这很容易:

$('span').click( ... )
Run Code Online (Sandbox Code Playgroud)

但是现在当我单击远离元素时,我希望触发另一个事件(例如,使文本变为正常粗细)。我需要以某种方式检测不在span元素内的单击。这与blur()事件非常相似,但是对于非INPUT元素。我不介意此点击是否仅在DIV元素内部而非页面的整个主体内检测到,顺便说一句。

我试图通过以下方法在非SPAN元素中触发事件:

$('div').click( ... ) // triggers in the span element
$('div').not('span').click( ... ) // still triggers in the span element
$('div').add('span').click( ... ) // triggers first from span, then div
Run Code Online (Sandbox Code Playgroud)

另一种解决方案是在click事件中读取事件的目标。这是以这种方式实现的示例:

$('div').click(function(e) {
  if (e.target.nodeName != "span")
     ...
});
Run Code Online (Sandbox Code Playgroud)

我想知道是否还有更优雅的解决方案,例如blur()。

Tat*_*nen 3

你的最后一个方法应该效果最好,即使它很混乱。这里有一点改进:

$('span').click(function() {
    var span = $(this);
    // Mark the span active somehow (you could use .data() instead)
    span.addClass('span-active');

    $('div').click(function(e) {
        // If the click was not inside the active span
        if(!$(e.target).hasClass('span-active')) {
            span.removeClass('span-active');
            // Remove the bind as it will be bound again on the next span click
            $('div').unbind('click');
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

它不干净,但应该可以工作。没有不必要的绑定,这应该是万无一失的(没有误报等)。