【问题标题】:javascript object, method to toggle values of different properties and striving to write DRY codejavascript对象,切换不同属性值的方法并努力编写DRY代码
【发布时间】:2014-11-10 16:50:20
【问题描述】:

我正在尝试为我的对象编写一个方法,该方法侦听要单击的按钮,并根据单击的按钮在 1 和 0 之间切换相应的对象属性。我可能偏离了轨道,但我可以用一种方法和“this”关键字?我下面的代码是我的进度,但我卡住了。http://jsfiddle.net/eh8L5cg1/

<input type="button" id="buttonOne" value="toggle buttonOne" />
<input type="button" id="buttonTwo" value="toggle buttonTwo" />
<input type="button" id="buttonThree"  value="toggle buttonThree" />

var controlPannel = {
    buttonOne : 0,
    buttonTwo :  0,
    buttonThree : 0
    toggleState: function() {

        $('button').click( function() {

            if (controlpannel.this == 0 ) {
                controlpannel.this = 1;
            } else {
                controlpannel.this = 0;
            }
        });

    }

}

【问题讨论】:

    标签: javascript html object methods logic


    【解决方案1】:

    是的,你可以;) 在代码中查看我的 cmets。这是更新小提琴的链接:http://jsfiddle.net/bmartinelle/eh8L5cg1/1/

     var controlPannel = {
        buttonOne : 0,
        buttonTwo :  0,
        buttonThree : 0,
        toggleState: function() {
            $(':button').click( function() {
                //"this" is the button - you need to fetch the id to access the property or your controlPannel
                console.log(controlPannel[this.id]);
                if (controlPannel[this.id] == 0 ) { //JS is case-sensitive - so make sure you use proper camelCasing
                    console.log("toggle to 1");
                    controlPannel[this.id] = 1;
                } else {
                    controlPannel[this.id] = 0;
                    console.log("toggle to 0");
                }
            });
         }
    
    }
    controlPannel.toggleState(); //be sure to actually assign the click handlers to your buttons!
    

    【讨论】:

    • 太棒了!这部分是什么意思 ':button' ? : 对我来说是新的。
    • 这是一种选择页面上所有“按钮”的方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 2015-09-22
    • 1970-01-01
    • 2016-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多