简体   繁体   中英

Jquery selector issue

I have the following html markup on my page,

<div id="sig_container">
    <div id="layer1" class="layer ui-draggable ui-resizable ui-resizable-autohide">
    <div id="layer2" class="layer ui-draggable ui-resizable ui-resizable-autohide">
    <div id="layer3" class="layer ui-draggable ui-resizable selected ui-resizable-autohide">
</div>

On this page I am trying to select the #sig_container div without selecting any of the children. However I am having an issue doing so. The selector either selects everything or nothing.

Thanks in advance Daniel

Edit: Sorry i should add I am trying to add a click event on the container. So i want the event to fire only when i click the container and not the children.

You can accomplish what you want by testing the event.target of the click event.

$('#sig_container').click(function( event ) {
    if( event.target === this ) {
        // the children were not clicked, so run your code
    }
});

The reason for this is that click events naturally bubble, so if you click one of the children, the event bubbles up to the sig_container and fires its handler.

With this solution, you make sure that the target of the event was actually the sig_container before it fires the code.

So basically:

  • this is the sig_container

  • event.target is the actual element clicked

  • if this is the same as the event.target run the code

This selector will select only the <div id="sig_container"> :

$('#sig_container')

If you think it's selecting the children as well, it's not:

alert($('#sig_container').length); // alerts 1
$('#sig_container')

should do the trick. If it doesn't, are you passing the html through anything that mangles IDs?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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