使用 if 语句实现相同功能的多个按钮

Multiple buttons for same function with if statement

我尝试制作我自己的案例功能,但一旦我在第一次点击时隐藏它们,我就无法将其设置为 "show stuff"。所以我的问题是我做错了什么,我该如何解决它,我应该怎么做呢?

我唯一的要求是多个按钮可以使用相同的代码来 show/hide 同一个对象 – 因此 oddClick 之类的东西将不起作用,因为这将需要不必要的点击才能获得 even/odd 再次(我想?)。

        $('.boxbtn').on('click', function () {
        var boxwidth = $('.box').width();
        console.log(boxwidth);
        console.log('-'+boxwidth+'px');
        var state = 1;

        if(state == 0) {  // I think we are trying to compare value here.
/*              alert("foo"); */
            var state = 1;
            console.log(state);
            /*show stuff here*/
        }
        else {
/*              alert("bar"); */
            var state = 0;
            console.log(state);
            /*hide stuff here*/
        }

    });

第 5 行:var state = 1;导致它总是进入 "else

var state = 1; //placed on global scope
 $('.boxbtn').on('click', function () {
        var boxwidth = $('.box').width();
        console.log(boxwidth);
        console.log('-'+boxwidth+'px');
        //var state = 1; removed from function scope

        if(state == 0) {
/*              alert("foo"); */
            state = 1;
            console.log(state);
            /*show stuff here*/
        }
        else {
/*              alert("bar"); */
            state = 0;
            console.log(state);
            /*hide stuff here*/
        }

    });

Fiddle: http://jsfiddle.net/8ubk5c0f/

在点击函数外声明 state 变量。

var state = 1; // Do not write inside click function scope

要检测对象的状态,您应该使用对象属性(而不是并行 state 变量)。

例如使用boxwidth的值。

更简单的方法:

$('.boxbtn').on('click', function () {
    var boxwidth = $('.box').width(); //Not sure why you want this
    console.log(boxwidth);
    console.log('-'+boxwidth+'px');
    var btnVal=$(this).text(); //get the button text
    if(btnVal=="Show Stuff") //if it is show stuff
    {
        $(this).text('Hide Stuff'); //change its text
        alert('stuff shown');
        /*show stuff here*/ //do the functionality
    }
    else {
        $(this).text('Show Stuff'); //change back to normal
        alert('stuff hidden');
        /*hide stuff here*/ //hide functionality
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="boxbtn">Show Stuff</button>

var state = 0; //placed on global scope

$('.boxbtn').on('click', function () {
    var boxwidth = $('.box').width();
    console.log(boxwidth);
    console.log('-'+boxwidth+'px');

    if(state == 0) {
        state=1;
        console.log(state);
    }
    else {
        state = 0;
        console.log(state);
    }

});