我想在我的构造函数SmartButton中运行一个名为makeHighlight的函数。 makeHighlight应该在我点击SmartButton对象(一个图像元素)时运行,这就是为什么我将属性'onclick'设置为makeHighlight的原因。我无法让它工作,它可能根本无法运行,或者在页面加载时立即运行。构造函数中的Javascript函数不工作onclick
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');
@jcolebrand它确实因为该事件的不,鼓泡。如果他指定了'href',那么它会将他带到另一个页面,但JavaScript仍然会启动(尽管他不会明显看到效果:))。 – freakish