在实例化之后,下面的js对象将生成指定的图像。我想要的是在浏览器中单击时让图像执行sayQuote
。建议?
function CharType()
{
this.charImage = function(whichImage)
{
var image = document.createElement("img");
image.src = "characters/"+whichImage;
document.body.appendChild(image);
}
function sayQuote()
{
alert(getQuote());
}
// this.onclick = sayQuote(); // nope, that doesn't do it!
}
实例化:
var stickfigure = new CharType();
stickfigure.charImage("stickfigure.png");
答案 0 :(得分:0)
试试这个。
function CharType()
{
function sayQuote()
{
alert(getQuote());
}
this.charImage = function(whichImage)
{
var image = document.createElement("img");
image.src = "characters/"+whichImage;
image.onclick = sayQuote;
document.body.appendChild(image);
}
}
基本上,在this.charImage中创建的图像是具有onclick属性的图像对象,而不是您创建的新对象。
答案 1 :(得分:0)
function CharType()
{
function sayQuote()
{
alert(getQuote());
}
this.charImage = function(whichImage)
{
var image = document.createElement("img");
image.src = "characters/"+whichImage;
image.addEventListener("click", this.sayQuote, false);
document.body.appendChild(image);
}
}