只有在Javascript / jQuery中没有默认值时才能执行操作?
我被问到div中任何地方的点击都会执行特定的操作(比如折叠它), 除非点击是在链接,按钮等上…
基本上,我喜欢event.preventDefault()
的反向。
有这么好的方法吗?
我在这里寻找一个通用的解决方案; 我不想对div的内容做太多考虑。
可能看起来像:
Clicking here should do stuff but not here, nor on the following image imagine buttons... input areas, ...
使用以下Javascript:
$("#click_me").click(function(){ if(black_magic) { $("#click_me").toggleClass("collapsed"); } });
您只需确保事件target
不是链接或按钮。
$('#clickhttps://stackoverflow.com/questions/3152075/how-to-do-an-action-only-when-there-is-no-default-in-javascript-jquery/_me').click(function(e) { interactive = 'a, button, input, textarea, video, map, object'; if($(event.target).closest(interactive).length == 0) ) { $("#clickhttps://stackoverflow.com/questions/3152075/how-to-do-an-action-only-when-there-is-no-default-in-javascript-jquery/_me").toggleClass("collapsed"); } });
只需将此处理程序添加到您的链接:
$("#clickhttps://stackoverflow.com/questions/3152075/how-to-do-an-action-only-when-there-is-no-default-in-javascript-jquery/_me a,button,input,textarea,video,map,object").click(function(e){ e.stopPropagation(); });
防止事件到达div(冒泡)。 它将停止,以便链接正常运行。
看到它在行动。 (点击预览)
Event bubbling
是这里的关键字。 将事件处理程序绑定到div并检查event target
以指定要执行的操作。
$('div.mydivclass').bind('click', function(event){ switch(event.target.id){ case 'idhttps://stackoverflow.com/questions/3152075/how-to-do-an-action-only-when-there-is-no-default-in-javascript-jquery/_ofhttps://stackoverflow.com/questions/3152075/how-to-do-an-action-only-when-there-is-no-default-in-javascript-jquery/_anhttps://stackoverflow.com/questions/3152075/how-to-do-an-action-only-when-there-is-no-default-in-javascript-jquery/_anchor':{ alert('anchor was clicked'); break; } case 'idhttps://stackoverflow.com/questions/3152075/how-to-do-an-action-only-when-there-is-no-default-in-javascript-jquery/_ofhttps://stackoverflow.com/questions/3152075/how-to-do-an-action-only-when-there-is-no-default-in-javascript-jquery/_ahttps://stackoverflow.com/questions/3152075/how-to-do-an-action-only-when-there-is-no-default-in-javascript-jquery/_span':{ alert('span was clicked'); break; } default: { alert('something else was clicked within me'); } } });
当然,您甚至可以检查目标tagName
或nodeType
。
function onClick(e){ var gates = "A,INPUT,TEXTAREA,SELECT"; var bound = this; var isCollapse = function ( node ){ if( node == bound ){ return true; } var re = new RegExp( "\\b" +node.nodeName+ "\\b", "g" ); return re.test( gates ) ? false : isCollapse( node.parentNode ); }; if( isCollapse( event.srcElement || e.target ) ){ alert( "collapse" ) // collapse() } } document.getElementById("clickhttps://stackoverflow.com/questions/3152075/how-to-do-an-action-only-when-there-is-no-default-in-javascript-jquery/_me").onclick = onClick;
*修复*适用于以下情况: a link