最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - click on link should not trigger parental onclick-event - Stack Overflow

programmeradmin2浏览0评论

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. I want that the event is only triggers if somebody clicks on the text or on the empty space inside the div container; 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');   
    }
} 

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. I want that the event is only triggers if somebody clicks on the text or on the empty space inside the div container; 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');   
    }
} 
Share Improve this question asked Apr 8, 2011 at 5:47 sauerburgersauerburger 5,1484 gold badges34 silver badges45 bronze badges 1
  • similar question – xkeshav Commented Apr 8, 2011 at 6:00
Add a ment  | 

4 Answers 4

Reset to default 8

Add a click handler to your link and stop event bubbleing to the parent 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. something like

onclick=foo(this)

The function foo looks like

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

Use the unbind http://api.jquery./unbind/

发布评论

评论列表(0)

  1. 暂无评论