将类函数添加到动态生成的按钮 JS/HTML

Adding a class function to a dynamically generated button JS/HTML

提问人:Alex 提问时间:11/28/2022 最后编辑:Alex 更新时间:11/28/2022 访问量:53

问:

我目前正在开发一个应用程序,该应用程序需要根据服务器端提供的数据自动生成一个 HTML 页面。我已经制作了当前的代码:

//Indicator class
class Button_class{
    constructor(name)
    {
        this.buttonAva = false;
        this.name = name;
        this.buttonIdHTML = '"' + name + "But" + '"'
    }   
     button_action()
    {
         //This is an abstract method
        console.log("foo")
    }
    //This method creates the button
    create_Button()
    {
        //Make sure that the method is only executed once
        if (this.buttonAva == false)
        {
            //Get the element id
            root22 = document.getElementById('root');
            //create the HTML code
            let html ="<button id="+this.indicatorIdHTML +"type='button' onclick = 'button_action()/> Click Me!";
            root22.insertAdjacentHTML("beforeend", html);
            html = "<p>"
            root22.insertAdjacentHTML("beforeend", html);
        }
    }
}
//----------------------------------------------------------

//function for setting up the page
 function process_init(){
    for (let i = 0; i < data.Indicators.length; i++){
        //Create the HTML for the indicators
        let temp_indi = new Indicator(data.Indicators[i]);
        indicators.push(temp_indi);
        
        indicators.push(data.Indicators[i])
        //Build the HTML page
        indicators[i].create_Indicator()
        indicators[i].create_Button()
       }
 }

我得到的错误如下:button_action未定义,我尝试在 THIS^.button_action() 下调用该函数,但这里没有结果。在JS中是否可以进行这样的设置,如果是,我该如何让它工作?提前谢谢你问候亚历克斯

JavaScript HTML 方法 this

评论

0赞 Professor Abronsius 11/28/2022
你能包括你如何初始化和调用类及其方法吗?

答:

0赞 johnsmh 11/28/2022 #1

要调用的方法与全局范围隔离,这意味着无法调用此方法,因为该函数未在全局范围中公开。

你可以通过使用该方法实现你正在尝试做的事情(假设你只是使用 vanilla js),并使用 直接将这个函数绑定到元素上。DOM.createElementelm.onclick

下面是一个示例,说明如何实现此目的

let btn = document.createElement('button', { id: this.indicatorIdHTML });
root22.insertAdjacentElement('beforeend', btn);
0赞 Professor Abronsius 11/28/2022 #2

您分配的 ID 存在错误 - 它不在引号内 (ok) 但会进入属性。type

标记本身需要关闭,这与不需要的输入类型不同。button</button>button

您不能像上面那样在字符串中添加内联,因此请在附加按钮后查询 DOM 并分配事件侦听器。button_method

class Button_class{
    constructor(name)
    {
        this.buttonAva = false;
        this.name = name;
        this.buttonIdHTML = '"' + name + "But" + '"'
    }   
     button_action()
    {
         //This is an abstract method
        console.log("foo")
    }
    //This method creates the button
    create_Button()
    {
        //Make sure that the method is only executed once
        if (this.buttonAva == false)
        {
            //Get the element id
            let root22 = document.getElementById('root');
            //create the HTML code
            let html =`<button id='${this.indicatorIdHTML}' type='button'>Click Me!</button>`;
            root22.insertAdjacentHTML("beforeend", html);
            html = "<p>"
            root22.insertAdjacentHTML("beforeend", html);
             root22.querySelector(`button[id="${this.indicatorIdHTML}"]`).addEventListener('click',this.button_action);
        }
    }
}


let bttn=new Button_class('geronimo')
    bttn.create_Button()
#root{
  border:1px solid red;
  padding:1rem;
}
#root button{
  border:1px solid blue;
}
<div id='root'></div>

0赞 jjj 11/28/2022 #3

您可以将点击事件绑定到您的按钮,如下所示。 箭头函数应该允许您访问。要调用的示例thisbutton_actionthis.name

//Indicator class
class Button_class{
    constructor(name)
    {
        this.buttonAva = false;
        this.name = name;
        this.buttonIdHTML = '"' + name + "But" + '"'
    }   
    
    button_action()
    {
         //This is an abstract method
        console.log("foo. my name is: " + this.name)
    }
    //This method creates the button
    create_Button()
    {
        //Make sure that the method is only executed once
        if (this.buttonAva == false)
        {
            //Get the element id
            const root22 = document.getElementById('root');
            
            // bind a click event to the button
            // and trigger the button_action
            let html =`<button id="${this.indicatorIdHTML}" type='button'>Click Me!</button>`;
            root22.innerHTML = html
            document.getElementById(this.indicatorIdHTML).addEventListener('click', ()=>this.button_action())
        }
    }
}


const b1 = new Button_class('My First Button!')
b1.create_Button()
<div id="root">
</div>

或者,通过更大的灵活性和面向未来的功能,您可以引用 HTML 按钮元素实例,而不是使用 id、class 或任何查询选择器。这样可以消除按钮名称重复导致 ID 重复时出现的问题。下面的示例还显示了如何使用按钮元素访问按钮元素,该元素可能可用于其他用途。this.elm

//Indicator class
class Button_class{
    constructor(name)
    {
        this.buttonAva = false;
        this.name = name;
        this.buttonIdHTML = '"' + name + "But" + '"'
        this.elm = null
    }   
    
    button_action()
    {
         //This is an abstract method
        console.log("foo. my name is: " + this.name)
    }
    //This method creates the button
    create_Button()
    {
        //Make sure that the method is only executed once
        if (this.buttonAva == false)
        {
            //Get the element id
            const root22 = document.getElementById('root');
            
            // create a button element and make a reference
            // you can access this.elm for other purposes
            this.elm = document.createElement("BUTTON");
            this.elm.setAttribute('type', 'button')
            this.elm.innerHTML = 'Click Me 2!'
            this.elm.addEventListener('click', ()=>this.button_action())
            root22.appendChild(this.elm)
        }
    }
}


const b1 = new Button_class('My Second Button!')
b1.create_Button()
console.log(b1.elm)
<div id="root">
</div>