Select a DIV but not a 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 on a DIV or image should call some function in jQuery:

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

I want to make it only warn the message when I click on a DIV or image, but not a link. Tried this:

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

but it didn’t work. Any ideas?

+3
source share
3 answers

The problem is probably in the event bubbles. What you can do is inside your click event check if nodeName/ tagNameis A or not, if so, interrupt the rest of your function and let the anchor just do it.

My jQuery is a little rusty because I do not use it 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.
    }
});
+9

- , div , , , , , event.stopPropagation(). , . - <a>, , :

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

Edit:

- , , <a>, , .

$('#menupull>*:not(a)').click( function(event) {
        alert( 'pullmenu clicked' );
});

http://jsfiddle.net/zCsLm/3/

+5

Your problem is that it $('#menupull:not(a)')selects an element with idfrom menupullwhich is not an element A.... well, obviously, #menupullis div., So the previous one is actually not so much. Instead, check what the targetclick means .

The easiest way is to just perform an alert only when the button has not been pressed A. If you click A, everything happens as usual (the link is executed, etc.). You can achieve this using : event.target.nodeName

$(function() {

    $('#menupull').click( function(event) {

        if (event.target.nodeName != 'A') {
            alert( 'pullmenu clicked' ); }
    });
});​

JsFiddle example

+3
source

Source: https://habr.com/ru/post/1767519/


All Articles