简体   繁体   中英

Fading parent div when clicking child link

I've looked for other ways to do this but have only found answers where it's the other way round (fading the child when the parent is clicked) - basically, I have boxes with goals in which can be accepted by clicking a link. What I want is for the box to fade out when you click the "accept" link - I'll add an AJAX call later so that this acceptance is stored in a database.

My jQuery code at the moment however only fades out the link itself when clicked. I'm unsure what to do now so that the whole box fades when the link is clicked. Thank you!

boxes.php

<div id='goal'>
    <div class='setby'>Set on 2013-12-31 16:02:35 by me</div>
    <div class='goal'>Climb Mount Kilimanjaro.</div>
    <div class='completeby'>
       Complete by 0000-00-00 00:00:00 - 
       <a id='accept' href='#'>Accept?</a>
    </div>
</div>

script.js

$(document).ready(function() {
    $('a#accept').click(function() {
        $(this).fadeOut('slow');
        });
    });

You want to use the closest function to find the parent goal div and fade that out:

$('a#accept').click(function() {
    $(this).closest('#goal').fadeOut('slow');        
});

By using closest it will work back up the through the parent elements until it finds the required one. This is useful as your HTML can change but as long as it is still has the same containing the jQuery code will work.

Also, as Jay mentioned, using an ID to identify the parent (and the accept link) is not a good idea as ID's should be unique within the document. Instead classes could be used for both:

<div class='goal-parent'>
    <div class='setby'>Set on 2013-12-31 16:02:35 by me</div>
    <div class='goal'>Climb Mount Kilimanjaro.</div>
    <div class='completeby'>
       Complete by 0000-00-00 00:00:00 - 
       <a class='accept' href='#'>Accept?</a>
    </div>
</div>

And the script would change to:

$('a.accept').click(function() {
    $(this).closest('.goal-parent').fadeOut('slow');       
});

Working example - http://jsfiddle.net/URLT8/

Just look for the parent -

$(document).ready(function() {
    $('a#accept').click(function() {
        $(this).closest('div').fadeOut('slow');
        });
    });

But you shouldn't be using duplicate id's in a page and I fear that you may have some ('accept', 'goal' etc.)

Like you said in your title. Target the parent of the link.

$(document).ready(function() {
    $('a#accept').click(function() {
        $(this).parent().fadeOut('slow');
    });
});

采用:

$(this).parent().fadeOut("slow");

用这个:

$(this).parent().parent().fadeOut("slow");

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