0

下面的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");
4

2 回答 2

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);
    }
}   
于 2013-09-03T03:24:04.700 回答
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 属性的图像对象,而不是您创建的围绕它的新对象。

于 2013-09-03T03:20:41.620 回答