简体   繁体   English

点击链接不应该触发父母onclick-event

[英]click on link should not trigger parental onclick-event

I've got the following code: 我有以下代码:

<div onclick="alert('div event');" style="cursor:pointer">
    some text
    <a href="asd.php" id="link">click</a>
</div>

When somebody clicks on the link the javaschipt event is triggered. 当有人点击链接时,会触发javaschipt事件。 I want that the event is only triggers if somebody clicks on the text or on the empty space inside the div container; 我希望只有当有人点击文本或div容器内的空白空间时才触发该事件; and not if somebody clicks on the link. 而不是如果有人点击链接。

Is it possible to call a function when the event is triggered, which checks on which elements the user has clicked. 是否可以在触发事件时调用函数,该函数检查用户单击的元素。 something link 一些链接

onclick="foo(caller);"

and

function foo(element){
    if(element!='link'){
        alert('yes');   
    }
} 

Add a click handler to your link and stop event bubbleing to the parent div. 在链接中添加一个单击处理程序,并停止将事件冒泡到父div。 Like this: 像这样:

$('#link').click(function(e) {
  e.stopPropagation();
});
$(function (){
  $('#link').click(function (e){ e.stopPropagation(); /*do other thing*/});
})

OnClick event you can pass the current object type. OnClick事件中,您可以传递当前对象类型。 something like 就像是

onclick=foo(this)

The function foo looks like 函数foo看起来像

 function foo(obj) {    
      if(obj.tagName != 'A') {
       alert('Yes')    
      } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM