制作图像' onclickable'在一个js对象中

时间:2013-09-03 03:12:46

标签: javascript image object onclick

在实例化之后,下面的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");

2 个答案:

答案 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);
    }
}