在其他容器中的锚点单击时显示隐藏元素 [英] Show hide elements on anchor click in a different container

查看:88
本文介绍了在其他容器中的锚点单击时显示隐藏元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要展示一堆不同的Flash标语.最好的办法是将它们全部隐藏起来,然后在单击标题时显示

I need to show a bunch of different flash banners. best I can figure is to hide them all, then show when the title is clicked

<!-- list that holds links -->
<ul id="bannerList" class="list">
    <li>Type
        <ul>
            <li><a href="#">Flash banner1 120x600</a></li>
        </ul>
    </li>

    <li>Other Type
        <ul>
            <li><a href="#">Flash banner2 120x600</a></li>
        </ul>
    </li>
</ul>

<div id="bannerTarget">
    <div class="vert">alpha</div>
    <div class="horiz">one</div>
    <div class="horiz">two</div>
    <div class="horiz">three</div>
    <div class="horiz">four</div>
</div>

#bannerTarget .vert {
width: 120px;
height: 600px;
margin: 0 auto;
float: left;
display: none;
}

#bannerTarget .horiz {
width: 728px;
height: 90px;
margin: 0 auto;
float: left;
display: none;
}

我不想为每个链接编写一个click函数以显示其对应的div,我如何使该函数更加实用?我在将链接链接到适当的div时遇到问题

I dont want to write a click function for each link to show it's corresponding div, how would I make the function more utilitarian? I'm having issues connecting a link to it's appropriate div

$("ul#bannerList li a").click(function(e) {
    e.preventDefault();
    $parent.addClass("selected").siblings().removeClass("selected");
    var href = $(this).attr('href');
    $href.css("display","block");
});

这行不通...有什么主意吗?

This doesn't work...any ideas?

推荐答案

您需要为div和类似的链接使用通用的命名约定:

You need to use a common naming convention for the div and the links like so:

<ul id="bannerList" class="list">
    <li>Type
        <ul>
            <li><a href="#" id="link-1">Flash banner1 120x600</a></li>
        </ul>
    </li>

    <li>Other Type
        <ul>
            <li><a href="#" id="link-2">Flash banner2 120x600</a></li>
        </ul>
    </li>
</ul>

<div id="bannerTarget">
    <div class="vert" id="div-1">alpha</div>
    <div class="horiz" id="div-2">one</div>
    <div class="horiz" id="div-3">two</div>
    <div class="horiz" id="div-4">three</div>
    <div class="horiz" id="div-5">four</div>
</div>

您的代码将变为:

$("ul#bannerList li a").click(function(e) {
    e.preventDefault();
    $('#bannerTarget > div').hide();
    var id = $(this).attr('id').replace('link-','');
    $('#div-'+id).show();
});

您也可以在不使用ID的情况下实现相同的功能,但是您需要保持链接顺序和div顺序相同:

You can also achieve the same without using ID's but you'll need to keep the link order and the div order the same:

$("ul#bannerList li a").click(function(e) {
    e.preventDefault();
    $('#bannerTarget > div').hide();
    var link_index = $(this).parent().index();
    $('#bannerTarget > div').each(function(){
        if( $(this).index() == link_index ){
            $(this).show();
        }
    });
});

这篇关于在其他容器中的锚点单击时显示隐藏元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆