开发者

How to swap fadeIn/fadeOut of dynamically created selectors

开发者 https://www.devze.com 2023-02-08 10:11 出处:网络
I am swapping out divs generated with a php foreach loop like this... <img class=\"trigger\" name=\"showme-<?php echo $stuff ?> ... >

I am swapping out divs generated with a php foreach loop like this...

<img class="trigger" name="showme-<?php echo $stuff ?> ... >

<div id="showme-<?php echo $stuff ?>" style="display:none"></div>

$('.trigger').click(function(){
    var num=$(this).attr("name");
    $('#'+num).fadeIn();

This works fine.. but my question is how do I n开发者_C百科ot just fade in these elements but also fade out the ones that are currently sitting there so I am only showing one showme-var div at a time? Because I do not know which one is currently showing I can not use the selector to identify who needs to be faded out. Can I add a wildcard "*" to the selector or maybe use .children of a parent div?


If you wrap all of these fadeIn/Out divs with a parent element, then you can simply grab all the siblings:

$('#' + num).fadeIn().siblings().fadeOut();

Provided there's nothing else in the same div of course.


Put a common class on the elements being faded in/out, and use that:

<div class="showHide" id="showme-<?php echo $stuff ?>" style="display:none"></div>
$('.trigger').click(function(){
    var num=$(this).attr("name");
    var shown = $('#'+num).fadeIn();      //show this one
    $('.showHide').not( shown ).fadeOut();  // hide all except for this one

Ultimately, the best solution will depend on your actual markup. If you provide more, you'll get a more accurate solution.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号