Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 views
in Technique[技术] by (71.8m points)

select the DIV but not the link inside it, jQuery question

I have the following div:

<div class='amazingmenu' id='menupull'>
    <img src='images/down.png' width=20 height=20 align='right'/>
    <div id='menupullhideme'>click the arrow to read the rest!<br /></div>
    more jokes on <a href='http://www.amazingjokes.com'>amazingjokes.com</a>
</div>

clicking the DIV or the image should execture some function in jQuery:

$('#menupull').click( function() {
          alert( 'pullmenu clicked' );
});

I want to make it so that it only alerts the message when I click the DIV or the image, but not the link. Tried this:

     $('#menupull:not(a)').click( function() {...

but that didn't work. Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is probably event bubbling.. what you could do, is inside your "click" event check if the nodeName/tagName is A or not, if it is, abort the rest of your function and let the anchor just do it's thing.

My jQuery is a little rusty as I don't use it much myself, but I think something like this..

$('#menupull').click( function(e) {
    var target  = $(e.target);
    if( target.is('a') ) {
        return true; // True, because we don't want to cancel the 'a' click.
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...