显示/隐藏具有基于数据属性的ID的div(onclick) [英] show/hide div with id based on data attribute (onclick)

查看:80
本文介绍了显示/隐藏具有基于数据属性的ID的div(onclick)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下列表:

<ul>
    <li><a href="" class="active" data-related="main">Main</a></li>
    <li><a href="" data-related="title_1">Title 1</a></li>
    <li><a href="" data-related="title_2">Title 2</a></li>
    <li><a href="" data-related="title_3">Title 3</a></li>
    <li><a href="" data-related="title_4">Title 4</a></li>
</ul>

以及以下div结构:

<div id="main">... Content ...</div>
<div id="title_1">... Content ...</div>
<div id="title_2">... Content ...</div>
<div id="title_3">... Content ...</div>
<div id="title_4">... Content ...</div>

开始时所有div都可见。 (由于Google以及没有JS的用户)

At the beginning all div's are visible. (Because of Google and for User without JS)

如果页面已加载,则应隐藏除主div以外的所有页面。如果我使用数据属性 title_1单击导航点,则相关的div应该可见,而主div也应该隐藏。活动类也应跳到新的活动导航点。 :)

If the page is loaded, all except the main div should be hidden. If I'm clicking on the navigation point with the data attribute "title_1" the related div should be visible and the main div should be hidden also. Also the class active should jump to the new active navigation point. :)

有可能吗?我不知道如何解决此问题。

Is that possible? I don't know how to get the solution for this problem.

感谢您的帮助!

推荐答案

您可以将ID与数据属性相匹配,如下所示:

you could match the ID with the data-attr like this:

$("div").each(function(){
     $(this).hide();
    if($(this).attr('id') == 'main') {
        $(this).show();
    }
});

$('a').on( "click", function(e) {
    e.preventDefault();
    var id = $(this).attr('data-related'); 
    $("div").each(function(){
        $(this).hide();
        if($(this).attr('id') == id) {
            $(this).show();
        }
    });
});

http://jsfiddle.net/mcko06ht/

http://jsfiddle.net/mcko06ht/

这篇关于显示/隐藏具有基于数据属性的ID的div(onclick)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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