将参数传递给onmouseover事件

pass parameter to onmouseover event

本文关键字:事件 onmouseover 参数传递      更新时间:2023-09-26

我试图传递一个参数onmouseover事件,像这样:

    function obj(id){
        if (!(this instanceof obj)) return new obj(id);
        this.element = (typeof id === 'string') ? document.getElementById(id) : id;
    }
    obj.prototype.call = function(content){
        this.element.addEventListener('mouseover',function(){
            console.log(content); // => undefined
            // My mistake is right here.
            var content = 'Hello';
        },false);
    };
//Edit
    function temp(){}
    temp.prototype.content = function(){
        return 'Hello World';
    };
    var temp = new temp();
    obj('id').call(temp.content());

我不明白为什么变量contentundefined。还有,我怎样才能弥补呢?

谁来帮帮我。我真的很感激。

我猜,你的回调是在不同的作用域或类似的东西执行的。

尝试使用闭包:

obj.prototype.call = function(content){
    this.element.addEventListener('mouseover',(function(content){
        return function(){
            console.log(content); // => undefined
        };
    })(content),false);
};

适合我:http://jsfiddle.net/ANB3z/

要么你的id是无效的(在这种情况下,你会得到一个不同的错误),或者你看到的"未定义"消息是在控制台中运行脚本本身的结果,而不是mouseover事件