【问题标题】:How to attr one link to multiple elements?如何将一个链接指向多个元素?
【发布时间】:2014-05-23 01:30:39
【问题描述】:

我不确定标题是否指向我的问题,但是: 我想用一个链接同时显示两个不同的元素(内容和图像)。它有点像内容和图像滑块,所以如果单击链接 1 attr content1 和 image1,如果单击链接 2 attr content2 和 image2 等等上..

这样我可以吸引盒子,但我怎么也叫图像呢?

$(".box").hide();
$(".box:first").show();

$("a").click(function() {
    var activeLink = $(this).attr("href"); 
    $("a").removeClass("active");
    $(".box").hide();
    $(activeLink).slideDown("normal");
    return false;
});

我已经来了这么远.. http://jsfiddle.net/2GR3W/2/

提前谢谢!

【问题讨论】:

  • 尝试为每个要隐藏/显示的元素分配唯一 ID。

标签: javascript jquery css


【解决方案1】:

试试:

$(document).ready(function () {
    // Text Box
    $(".box, .img").hide();
    $(".box:first,.img:first").show();
    $("a").click(function (e) {
        var idx=$(this).index();
        e.preventDefault();
        var activeLink = $(this).attr("href");
        $("a").removeClass("active");
        $(".box, .img").hide();
        $('.container div').eq(idx).slideDown("normal");
        $('.container img').eq(idx).slideDown("normal");
    });
});

jsFiddle example

【讨论】:

    【解决方案2】:

    尝试重构您的图像 ID 引用以遵循以链接 href 值命名的约定。

    <img id="box3-img" class="img"  src="asd.jpg" width="300" height="200" alt="img3"/>
    

    然后您可以将“href”属性值视为图像 ID 的前缀:

    $(activeLink + "-img").show();
    

    http://jsfiddle.net/2GR3W/5/

    【讨论】:

    • 听起来很有趣!但是 img id = box3-img 不是这里的 id 名称?我真的没有用约定重构 img id 吗??..
    【解决方案3】:

    我的解决方案是:

    $(document).ready(function() {
    
        $('.links').on('click','a',function() {
            if(!$(this).hasClass('active')){
                $('.links a').removeClass('active')
                $(this).addClass('active');
                $('.container').find('.box, img').hide();
                $('.container').find('.box').eq($(this).index()).slideDown('normal');
                $('.container').find('img').eq($(this).index()).fadeIn('normal');
            }
        }); 
    
    });
    
    $(window).load(function(){
        $('.links').find('a:nth-child(1)').trigger('click');
    });
    

    小提琴:

    http://jsfiddle.net/2GR3W/7/

    使用此代码,您可以将无穷大 &lt;a/&gt;&lt;div class="box"/&gt;&lt;img/&gt;,它总是会在相同的“顺序”中找到 .boximg 并显示它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      相关资源
      最近更新 更多