if语句具有相同功能的多个按钮

时间:2015-09-15 09:23:22

标签: javascript jquery button switch-statement case

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

我唯一的要求是多个按钮可以使用相同的代码来显示/隐藏同一个对象 - 因此像oddClick这样的东西将无法工作,因为这需要不必要的点击才能获得偶数/奇数(I认为?)。

        $('.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 个答案:

答案 0 :(得分:1)

这一行5:var state = 1;导致它总是进入"否则

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*/
        }

    });

小提琴:http://jsfiddle.net/8ubk5c0f/

答案 1 :(得分:0)

在点击功能之外声明状态变量。

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

答案 2 :(得分:0)

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

例如,使用boxwidth的值。

答案 3 :(得分:0)

以更简单的方式:



$('.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>
&#13;
&#13;
&#13;

答案 4 :(得分:-1)

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);
    }

});