JQuery:切换隐藏/显示div元素 - 是否有更有效的方法?

时间:2014-07-25 12:47:06

标签: jquery html toggle

我在四个div元素之间切换:

<!-- Toggle controls -->
<span id="todayToggle">
    Today
</span>
<span id="tomorrowToggle">
    Tomorrow
</span>
<span id="thirdToggle">
   Third day
</span>
<span id="fourthToggle">
   Fourth day
</span>


<!-- Divs to hide/show -->
<div class="premium" id="today">
    <h3>First day</h3>
</div>

<div class="premium" id="tomorrow">
    <h3>Second day</h3>
</div>

<div class="premium" id="third-day">
    <h3>Third day</h3>
</div>

<div class="premium" id="fourth-day">
    <h3>Fourth day</h3>
</div>

这是我用来隐藏/显示各个元素的JQuery。页面加载时默认显示“今天”div。我的目的是简单地显示所选的div并隐藏其他三个,具体取决于所选的元素。

<script>
$(document).ready(function() {

    $("#tomorrow, #third-day, #fourth-day").hide();
    $("#todayToggle").click(function() {
        $("#tomorrow, #third-day, #fourth-day").hide();
        $("#today").show();
    });

    $("#tomorrowToggle").click(function() {
        $("#today, #third-day, #fourth-day").hide();
        $("#tomorrow").show();
    });

    $("#thirdToggle").click(function() {
        $("#today, #tomorrow, #fourth-day").hide();
        $("#third-day").show();
    });

    $("#fourthToggle").click(function() {
        $("#today, #tomorrow, #third-day").hide();
        $("#fourth-day").show();
    });

});
</script>

这很有效,但看起来效率很低,而且我确信有一个更清洁,更实用的解决方案。任何帮助和建议都非常感谢。

2 个答案:

答案 0 :(得分:3)

一种方法,但涉及更改后两个id元素的div

$('span[id]').on('click', function(){
    var clicked = this;
    $('.premium').hide().filter(function(){
        return this.id == clicked.id.replace('Toggle','');
    }).show();
}).first().click();

JS Fiddle demo

或者,基于id映射到所单击元素的文本:

$('span[id]').on('click', function(){
    var clicked = $(this);
    $('.premium').hide().filter(function(){
        return this.id === $.trim(clicked.text()).toLowerCase().replace(/\s+/g,'-');
    }).show();
}).first().click();

JS Fiddle demo

或者,也许最后,使用被点击元素的索引(假设被点击的元素和要显示的元素共享相同的索引):

$('span[id]').on('click', function(){
    var clicked = $(this);
    $('.premium').hide().eq(clicked.index('span[id]')).show();
}).first().click();

JS Fiddle demo

参考文献:

答案 1 :(得分:2)

我最近使用过这样的东西:

DEMO

在触发元素中添加data属性:

<span class="toggle_trigger" data-toggle-target="#today">
    Today
</span>

然后使用该属性查找目标。所以你的代码将成为:

$(".premium").hide(); /* hide all via class instead of ID's */
$('.toggle_trigger').on('click',function() {
    var target = $(this).data('toggle-target');
    $(".premium").hide();
    $(target).show();
});

或略短的版本:

$('.toggle_trigger').on('click',function() {
    $(".premium").hide();
    $($(this).data('toggle-target')).show();
});