如何从对象中提取类名或ID?

时间:2018-12-14 13:47:23

标签: javascript

根据我的理解,将所有DOM选择器都保留在一个对象内是一种很好的做法,因为如果修改了html,则只需更改该对象即可,而无需查看整个代码。但是,如何从该对象获取类名或ID?

我以前做过的例子。 https://codepen.io/anon/pen/vvLoqJ?editors=1111

我要做什么:

很显然,这是行不通的,因为我试图添加带有对象的字符串。但是,如果有一种方法可以添加该字符串类位置,以便按钮2在不修改elements对象的情况下就可以工作。先感谢您。 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();

2 个答案:

答案 0 :(得分:0)

您正在寻找类似的东西吗?

    class buttonRoll {
      constructor(base_ClassName) {
        this.button_1 = document.querySelector('.'+base_ClassName);
        this.button_2 = document.querySelector('.'+base_ClassName+'-2');

        this.button_1.onclick = (e)=>this.button_1_click(e);
        this.button_2.onclick = (e)=>this.button_2_click(e);

      }
      button_1_click(e){
        console.log('button_1_click');
      }
      button_2_click(e){
        console.log('button_2_click');
      }
    }

    buttonRolls = new buttonRoll('button--roll');
    <button class = "button--roll">First Roll</button>

    <button class = "button--roll-2">Second Roll</button>

答案 1 :(得分:0)

在这种情况下,通过使用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>