假设我有以下 HTML:
<div>
<span>span text</span> div text <span>some more text</span>
</div>
我想这样做,以便当我单击 span 时,它会触发一些事件(例如,使文本变粗),这很容易:
$('span').click( ... )
但是现在当我点击离开元素时,我想要触发另一个事件(例如,使文本正常重量)。我需要以某种方式检测不在 span 元素内的点击。这与 blur() 事件非常相似,但适用于非 INPUT 元素。我不介意是否仅在 DIV 元素内部检测到此点击,而不是在页面的整个 BODY 中检测到,顺便说一句。
我尝试使用以下内容在非 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
另一种解决方案是在点击事件中读取事件的目标。这是以这种方式实现它的示例:
$('div').click(function(e) {
if (e.target.nodeName != "span")
...
});
我想知道是否有像 blur() 这样更优雅的解决方案。