在jQuery中检测背景点击 [英] Detect background click in jQuery
问题描述
说我有以下HTML:
<div>
<span>span text</span> div text <span>some more text</span>
</div>
我要创建它,这样当我单击span时,它将触发一些事件(例如,使文本变为粗体),这很容易:
I want to make it so that when I click on span, it will trigger some event (e.g. to make the text bold), that's easy:
$('span').click( ... )
但是现在我点击离开元素时,我希望触发另一个事件(例如,使文本变为正常粗细).我需要以某种方式检测不在span元素内的单击.这与blur()事件非常相似,但对于非INPUT元素而言.我不介意此点击是否仅在DIV元素内而不是页面的整个主体内检测到,顺便说一句.
But now I when I click away from the element, I want another event to trigger (e.g. to make the text normal weight). I need to detect, somehow, a click not inside the span element. This is very similar to the blur() event, but for non INPUT elements. I don't mind if this click is only detected inside the DIV element and not the entire BODY of the page, btw.
我试图通过以下方法在非SPAN元素中触发事件:
I tried to get an event to trigger in non-SPAN elements with the following:
$('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
另一种解决方案是在click事件中读取事件的目标.这是以这种方式实现的示例:
Another solution would be to read the event's target inside the click event. Here's an example of implementing it this way:
$('div').click(function(e) {
if (e.target.nodeName != "span")
...
});
我想知道是否还有更优雅的解决方案,例如blur().
I was wondering if there was a more elegant solution like blur() though.
推荐答案
即使杂乱无章,您的最后一个方法也应该效果最好.这里有一些改进:
Your last method should work best even if it's messy. Here's a little refinement:
$('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');
}
});
});
这不干净,但是应该可以.没有不必要的绑定,这应该是万无一失的(没有误报等).
It's not clean, but it should work. No unnecessary binds and this should be foolproof (no false positives etc).
这篇关于在jQuery中检测背景点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!