jQuery从链接切换联系人

jQuery switching contaiers from links

本文关键字:联系人 链接 jQuery      更新时间:2023-09-26

嗨,伙计们,我正在努力让下面的内容发挥作用,我有一组4个链接,我需要显示一个3的div容器和另一个1的div容器,并切换回等等…有什么想法吗?

<div class="content active">
 this is a main container
</div>
<div class="content news">
 this is a news container
</div>
<dl>
<dd><a href="">link 1</a></dd>
<dd><a href="">link 1</a></dd>
<dd class="news"><a href="">link 1</a></dd>
<dd><a href="">link 1</a></dd>
</dl>

需要默认显示主容器,当点击新的DD项目切换到新容器时,但如果点击其他DD链接,则切换回我的js,当然这不起作用哈哈

$('dd a').bind('click',function(){
    if($('dd').hasClass('news')) {
        $('.content').removeClass('active');
        $('.content.news').addClass('active');
    } else if(!$('dd').hasClass('news')) {
        $('.content.news').removeClass('active');
        $('.content').addClass('active');
    }
});

提前感谢

您是否使用CSS来显示div w/class"active"?

您也可以用.hide()替换.removeClass('active'),用.show() 替换.addClass('active')

我希望你需要这样的

$('.news').css('display','none');
$('dd').click(function(){
if($(this).hasClass('news'))
{
$('.news').css('display','visible');    
}
}):

这可能是最简单、最干净的答案:

$('dd a').bind('click',function(){
    $('.content').hide();
    if($(this).parent('dd').hasClass('news')) {
        $('.content.news').show();
    } else {
        $('.content.active').show();
    }
});

您可能需要将"活动"类重命名为更具描述性的类。

我认为您可能会让这件事变得更加复杂。这是一个更容易思考问题的地方。您希望显示一个容器,单击时显示另一个,然后使用其他链接返回。

对于ID来说,这是一项理想的工作,因为它们可以更容易地识别一个框,但可以随意用类替换它。这是ID为的HTML

<div class="content active" id="default">
 this is a main container
</div>
<div class="content" id="news">
 this is a news container
</div>
<dl>
<dd><a href="javascript:show()">link 1</a></dd>
<dd><a href="javascript:show()">link 1</a></dd>
<dd><a href="javascript:show('news')">link 1</a></dd>
<dd><a href="javascript:show()">link 1</a></dd>
</dl>

它还包括一些javascript链接,但您也可以将其移动到jQuery中的点击事件中。我只是觉得它更清楚,因为我们实际上不需要读取数据,我们直接从链接中传递数据。[警告:有些人不喜欢这个,但它可能很有用]。

这是javascript:

function show(id){
    $(".content").removeClass("active");
    if($("#" + id).length)
        // in the if statement above you could even add && !$("#" + id).hasClass("active")
        // to default back to default if the current one is already active
        $("#" + id).addClass("active");
    else
        $("#default").addClass("active");
}

这对我很有效。请注意,如果没有找到id,或者如果你像我在评论中提到的那样添加hasClass(活动),我决定显示默认框,以隐藏当前活动的框。您可以将其转换为jQuery,但必须使用数据元素来传递ID,或者将其包含在href中并阻止默认值。我发现这种方法更容易。

编辑:JQuery解决方案

将href替换为div引用的HTML(包括用于安全和回退的哈希)。

<dl>
<dd><a href="#">link 1</a></dd>
<dd><a href="#">link 1</a></dd>
<dd><a href="#news">link 1</a></dd>
<dd><a href="#">link 1</a></dd>
</dl>

JQuery代码读取正确的ID并显示:

$("dd a").click(function(event){
    // Prevent the link from going anywhere
    event.preventDefault();
    $(".content").removeClass("active");
    // Get the link DIV from the href (this will fallback to scroll-page-to-div without JS)
    var id = $(this).attr("href");
    if($(id).length)
        $(id).addClass("active");
    else
        $("#default").addClass("active");
});