我正试图为我的对象编写一个方法,该方法监听要单击的按钮,并根据单击的按钮在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;
}
});
}
}
可以;)请参阅我在代码中的注释。这里有一个更新小提琴的链接: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!