简体   繁体   English

构造函数中的Javascript函数不适用于onclick

[英]Javascript function in constructor not working for onclick

I'm trying to run a function called makeHighlight within my constructor SmartButton. 我正在尝试在构造函数SmartButton中运行一个名为makeHighlight的函数。 makeHighlight is supposed to run whenever I click on the SmartButton object (an image element) which is why I set the attribute 'onclick' to makeHighlight. 每当我点击SmartButton对象(图像元素)时,makeHighlight就会运行,这就是我将属性'onclick'设置为makeHighlight的原因。 I can't get it to work, it either doesn't run at all or runs instantaneously when the page loads. 我无法让它工作,它要么根本不运行,要么在页面加载时立即运行。

function SmartButton(buttonId, defaultImage, highlightImage, helpMsg) {
    var newLink = document.createElement('a');
        newLink.setAttribute('href', '#');

    var newImg = document.createElement('img');
        newImg.setAttribute('src', defaultImage);
        newImg.setAttribute('id', buttonId);
        newImg.setAttribute('onclick', "makeHighlight()");

    document.body.appendChild(newLink);
    newLink.appendChild(newImg);

    this.buttonId = buttonId;
    this.defaultImage = defaultImage;
    this.highlightImage = highlightImage;
    this.helpMsg = helpMsg;

    function makeHighlight() {
        newImg.setAttribute('src', highlightImage);
        console.log(this);
    }

}   

button1 = new SmartButton('button1', 'button1off.jpg', 'button1on.jpg', 'sup');

You defined makeHighlight in the scope of SmartButton function. 您定义makeHighlight在范围SmartButton功能。 Thus newImg when clicked does not see it. 因此,单击newImg时看不到它。 Try this code (inside SmartButton ): 试试这段代码(在SmartButton ):

function makeHighlight() {
    newImg.setAttribute('src', highlightImage);
    console.log(this);
}
newImg.onclick = makeHighlight;

(note the lack of brackets in the last line) and remove this line: (注意最后一行没有括号)并删除此行:

newImg.setAttribute('onclick', "makeHighlight()");

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

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