简体   繁体   中英

Add event handlers to grand children

I have some html code having hierarchy as

<div id="a">
    <span>
        <span id="s1">...</span>
        <span id="s2">...</span>
        <span id="s3">...</span>
    </span>
</div>

I want to attach event handlers to s1,s2,s3 And assume that I don't know id div.span. I tried out

$('#a span span').click(function(){
    alert('called');
});

But this does not work. Is there any other option to access grand children of an element.

Try using on() and > * > * . The > means children. Without it, it would mean descendants. Then first > * is children, the second > * is the children of the children or "grand children"

$('#a > * > *').on('click', function() {
    alert('called');
});

i removed my first answer (the delegated version of on() ) one since I can't get it to work on jsFiddle. I'm not sure why it doesn't work.

$('#a>span>span').click(function(){
    alert('called');
});

it will look into #a and all direct child of #a that is a span it looks after direct child in that span

<div id="a">
    <span>
        <span id="s1">hit</span>
        <span id="s2">hit</span>
        <span id="s3">hit</span>
    </span>
    <span>
        <strong>
            <span>Wont hit</span>
        </strong>
    </span>
</div>

with that markup all span with the text hit will have a click event on them. jsfiddle test: http://jsfiddle.net/voigtan/TeN2q/

You can also use event delegation here. Assing the click handler to the parent element only, check within the handler from which element the click occured, and act accordingly. For example:

$('#a').click(function(e){
  e = e || event;
  var src = e.target || e.srcElement;
  if (/^s/i.test(src.id)){ /* actions */ }
  return true;
});

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