javascript 对象,切换不同属性值的方法和努力编写 DRY 代码

标签 javascript html object methods logic

我正在尝试为我的对象编写一个方法来监听要单击的按钮,并根据单击哪个按钮在 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;
            }
        });

    }

}

最佳答案

是的,你可以 ;) 请参阅我在代码中的评论。这是更新后的 fiddle 的链接: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!

关于javascript 对象,切换不同属性值的方法和努力编写 DRY 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25877218/

相关文章:

javascript - 递归地 trim 对象键和值中的空格

Javascript - 删除一个对象作为函数的参数

javascript - 为什么在使用 d3 创建 AngularJS 指令时使用 element[0] 而不是 element?

c# - 动态创建和删除对象

javascript - 使用 Ajax 发送数据

html - 我的 class/id/highlight 标签不工作

html - 难以捉摸的图标字体不适用于任何版本的 IE

javascript - 如何配置 Phantom.js?

javascript - 无法选择下拉值以及如何在选择每个下拉列表后显示动态字段?

javascript - 使表格中的列仅与最长文本元素的文本一样宽