根据我的理解,将所有 DOM 选择器保存在一个对象中是一种很好的做法,因为如果修改了 html,您只需要更改该对象,而无需查看整个代码。但是,如何从该对象获取类名或 id?
我以前做的例子。https://codepen.io/anon/pen/vvLoqJ?editors=1111
我正在尝试做的事情:
显然是行不通的,因为我试图用对象添加字符串。但是,如果有一种方法可以添加该字符串类的位置,以便按钮 2 可以在不修改元素对象的情况下工作。先感谢您。https://codepen.io/anon/pen/WLweom?editors=1111
HTML
<button class = "button--roll">First Roll</button>
<button class = "button--roll-2">Second Roll</button>
脚本
const elements = {
buttonRoll: document.querySelector(".button--roll"),
};
class buttonRoll{
constructor(){
// Properties
this.buttonRoll = elements.buttonRoll;
// Methods
this.events;
}
events(){
let roll = "-2";
// this.buttonRoll + roll.addEventListener('click', () => this.buttonRoll2());
console.log(this.buttonRoll);
}
buttonRoll2(){
console.log("second button is clicked");
}
}
buttonRoll = new buttonRoll;
buttonRoll.events();
在这种情况下,通过使用您的 const 元素:
const elements = {
buttonRoll: document.querySelector(".button--roll"),
};
class buttonRoll {
constructor() {
let base_ClassName = elements.buttonRoll.className;
this.button_1 = elements.buttonRoll;
this.button_2 = document.querySelector('.'+base_ClassName+'-2');
this.button_1.onclick = (e)=>this.button_x_click(e);
this.button_2.onclick = (e)=>this.button_x_click(e);
}
button_x_click(e){
console.log(e.target.className);
}
}
buttonRolls = new buttonRoll();
<button class = "button--roll">First Roll</button>
<button class = "button--roll-2">Second Roll</button>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句