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
348 views
in Technique[技术] by (71.8m points)

javascript - jQuery - on() function when a div is clicked, but not when a child of that div is clicked

I have one large rectangular parent div inside which there are many child divs. I have an on(click) function that runs when the parent div is clicked, but by default it also runs when anything within the parent div is clicked (including the children).

However, I don't want the on(click) function to run when one specific child of the parent is clicked. How do I make a selector that selects the parent div and everything in it apart from this one child?

Thanks

<div class="box"">

<div class="overlay"><div id="text"></div></div>
<div class="slide">
    <div class="slideleft"></div>
    <div class="slideright">
        <span class="upvote">Upvote</span>
        <span class="counter"></span>
    </div>
</div>

</div>

Now, this is all within the 'box' div and you can see a demo of what happens here. If you click the upvote button after having already clicked on a box, then the thing slides back down which I don't want it to. This is the code I'm trying to use right now for this but it's not working:

$("body").on("click", ".box", function(e){
        if(e.target.class == 'upvote') {
            return false;
        } else {
                $(this).children('.slide').slideToggle(150);
                $(this).children('overlay').css('background-color', 'rgba(0,0,0,0)');
            }
});
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Working Fiddle

$("body").on("click", ".box", function (e) {
if (e.target.className != 'upvote') {
  $(this).children('.slide').slideToggle(150);
  $(this).children('.overlay').css('background-color', 'rgba(0,0,0,0)');
}
});

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

...