1

我希望在单击按钮时切换两个 div(一个显示而不是另一个),但是当我单击按钮时,按钮消失并且不切换 div。

<button id="change" class="btn">Change</button>
<div id="FTE" style="border:2px solid #09F">
    Contents 1
</div>

<div id="ETF" style="border:2px solid #09F">
    Contents 2
</div>

$(document).ready(function () {
    $("#ETF").show();
    $("#FTE").hide();
    $("#change").click(function () {
        $("#change").toggle(function (){
            $("#change").text("First");
            $("#FTE").hide(1000);
        }, function() {
            $("#change").text("Second");
            $("#ETF").show(1000);
        });
    });
});
4

2 回答 2

3

http://jsbin.com/alomew/4/edit

$(function () { // DOM ready shorthand

    $("#ETF").show();
    $("#FTE").hide();

    var changeTxt = ["Second","First"];

    $("#change").click(function () {       
        $(this).text( changeTxt.reverse()[0] );
        $("#FTE, #ETF").toggle( 1000 );      
    });

});

我厌倦了使用条件运算符来切换两个值,
$(this).text( $(this).text() == "foo" ? "bar" : "foo" );
所以最近我想出了一个不错的小技巧:

changeTxt.reverse()[0](就像名字已经暗示的那样)将在每次单击我们的changeTxtArray 时反转并获取第一个(0 索引)Array Key 值。

附加文档:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse

于 2013-08-06T21:08:37.987 回答
2

.toggle() 更改匹配元素(按钮)的可见性。然后你尝试隐藏已经隐藏的 FTE 元素并显示已经显示的 ETF 元素。

于 2013-08-06T21:00:28.010 回答