假设我有以下HTML:
<div>
<span>span text</span> div text <span>some more text</span>
</div>我想让它当我点击span时,它会触发一些事件(例如,将文本设为粗体),这很容易:
$('span').click( ... )但现在,当我离开元素时,我希望触发另一个事件(例如,使文本正常权重)。我需要以某种方式检测不在span元素内部的单击。这非常类似于blur()事件,但用于非输入元素。我不介意这个点击只在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另一种解决方案是在click事件中读取事件的目标。下面是一个以这种方式实现它的示例:
$('div').click(function(e) {
if (e.target.nodeName != "span")
...
});我想知道是否有像blur()这样更优雅的解决方案。
发布于 2010-01-14 05:27:25
即使最后一个方法很混乱,它也应该工作得最好。下面是一些改进:
$('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');
}
});
});它不干净,但它应该可以工作。没有不必要的绑定,这应该是万无一失的(没有误报等)。
发布于 2011-12-29 12:50:22
根据我的研究,我认为stopPropagation函数是最合适的。例如:
$("#something_clickable a").click(function(e) {
e.stopPropagation();
})有关类似问题,请参阅How do I prevent a parent's onclick event from firing when a child anchor is clicked?。
发布于 2010-01-14 05:25:29
在jQuery发布之前,我想出了一个解决这个问题的方案……
Determine if any Other Outside Element was Clicked with Javascript
document.onclick = function() {
if(clickedOutsideElement('divTest'))
alert('Outside the element!');
else
alert('Inside the element!');
}
function clickedOutsideElement(elemId) {
var theElem = getEventTarget(window.event);
while(theElem != null) {
if(theElem.id == elemId)
return false;
theElem = theElem.offsetParent;
}
return true;
}
function getEventTarget(evt) {
var targ = (evt.target) ? evt.target : evt.srcElement;
if(targ != null) {
if(targ.nodeType == 3)
targ = targ.parentNode;
}
return targ;
}https://stackoverflow.com/questions/2060354
复制相似问题