繁体   English   中英

使用 Javascript class 和 addEventListener 更改 HTML 元素的文本

[英]Changing text of HTML element using Javascript class and addEventListener

I want to change the text of an HTML div using a Javascript class object by attaching addEventListener function to an HTML button. 单击按钮时,不会在 div 中显示“红色”,而是显示“未定义”文本。 但是,如果我使用 class object 直接调用 function changeColor ,则会显示正确的值。 我为这种天真的查询在该领域较新表示歉意。 我正在关注 w3schools 上的教程。 我的代码如下:

 class Header { constructor() { this.mystring = "Red"; } changeColor() { document.getElementById("div1").innerHTML = this.mystring; } } //create object of class const myheader = new Header(); // This code does not work and shows undefined in the div document.getElementById("btn").addEventListener('click', myheader.changeColor); // This code works and shows Red in the div // myheader.changeColor();
 <button id="btn">Click Me!</button> <div id="div1"></div>

您将myheader.changeColor function 作为没有上下文的参数发送。 只需使用绑定方法。

 class Header { constructor() { this.mystring = "Red"; } changeColor() { document.getElementById("div1").innerHTML = this.mystring; } } //create object of class const myheader = new Header(); // This code does not work and shows undefined in the div document.getElementById("btn").addEventListener('click', myheader.changeColor.bind(myheader)); // This code works and shows Red in the div // myheader.changeColor();
 <button id="btn">Click Me!</button> <div id="div1"></div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM