我正在处理按钮程序。我有一个Button
对象,分配给HTML中的每个按钮。由于有不同类型的按钮,我希望有一个不同的构造函数来使对象适合每种类型。
我理解如何调用这些单独的构造函数,但我不知道在构造函数中放置什么以使它将某些变量应用于Button
对象。
示例按钮对象:
var Button = function(){
if (buttonType == 'type1'){
buttonType1(); //set onclick, onmouseover/mouseout, onmousedown/mouseup
}
else{
buttonType2(); //set different ways to handle events
}
}
如何创建Button
对象:
var buttons = document.getElementsByClassName('button');
Buttons = new Buttons_Objs(); //An object to store references to all Button Objs.
for (i = 0 ; i < buttons.length ; i++){
button = buttons[i];
buttonType = button.getAttribute('type');
Buttons['button' + i] = new Button(button, buttonType);
}
我如何构建这些函数来设置onclick和东西,如果我不希望它们挤占我的Button
对象,那么它将在哪里存储它们。
答案 0 :(得分:1)
你所呈现的只是一个普通的javascript函数(不是构造函数),你可以添加一个这样的参数:
var Button = function(buttonType){
if (buttonType == 'type1'){
buttonType1(); //set onclick, onmouseover/mouseout, onmousedown/mouseup
}
else{
buttonType2(); //set different ways to handle events
}
}
然后,你会这样打电话:
Button("type1");