开发者

fancybox open relative div

开发者 https://www.devze.com 2023-02-18 23:51 出处:网络
I\'m trying to figure out how to open a div in fancybox relatively from the link that was clicked. <div class=\"tool\">

I'm trying to figure out how to open a div in fancybox relatively from the link that was clicked.

<div class="tool">              
    <ul>            
        <li><span class="more-info"><a href="#" title="View more info">?</a></span>         
            <div class="help">This is the help text</div>           
        </li>
    </ul>
</div>

I know I can add something like #uniqueDiv to a and then a div with id uniqueDiv, however I would prefer that when the link is clicked, it opens the closest div with clas开发者_JAVA技巧s help.

I tried something like this with no luck:

$('.more-info a').click(function(e){
    $(this).parent().next().fancybox();
    e.preventDefault();
});

Any help would be much appreciated.

-Ryan


I thought about this problem for a few more hours and decided to approach it differently, since I was pretty much at a dead end. I was thinking that if I can't target a relative div, maybe I can then auto-assign the href and id values, so each link can then be targeted via its id.

This actually worked out beautifully and meets all my requirements:

$('.more-info a').each(function(index){
    var x = index + 1;
    $(this).attr('href', '#box' + x);
    var li = $(this).parent().parent();
    $('.help', li).attr('id', 'box' + x);
}).fancybox();
  1. $('.more-info a').each(function(index){ I target all my links and loop through them.
  2. var x = index + 1; The index starts at 0, but for readability, I start it at 1.
  3. $(this).attr('href', '#box' + x); I take the current link's href value (currently #) and replace it with #box[INDEX] where index is a unique, auto-incrementing number.
  4. var li = $(this).parent().parent(); I move back a view elements so I can hone in on my hidden div .help.
  5. $('.help', li).attr('id', 'box' + x); I now target the .help div and add an attribute called id and set it to box[INDEX]. I now have the necessary association between link and hidden div so that fancybox can do its magic.
  6. }).fancybox(); This lets fancybox know to open my links with it.

jQuery functions used: .each(), .attr(), .parent()

Any suggestions or improvements are still appreciated.

-Ryan

0

精彩评论

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

关注公众号