Javascript 将参数传递给onmouseover事件

Javascript 将参数传递给onmouseover事件,javascript,onmouseover,Javascript,Onmouseover,我试图将参数传递给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){ t

我试图将参数传递给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());
我不明白为什么变量
content
未定义的
。还有,我怎样才能做到正确呢


请有人帮我解决这个问题。我真的很感激。

我想,您的回调是在不同的范围或类似的情况下执行的

尝试使用闭包:

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


您的id无效(在这种情况下,您可能会收到另一个错误),或者您看到的“未定义”消息是在控制台中运行脚本本身的结果,而不是
mouseover
事件。

我不明白为什么变量内容未定义-。我刚刚编辑了我的问题。实际上,我从另一个作用域调用了
Hello World
。经过编辑的代码也可以很好地工作。对于OP:在发布之前,你不能检查一下你试图在JSFIDLE中提供的示例吗?我永远不会理解为什么人们包含的代码不是给他们带来问题的实际代码。这样包装
内容是没有用的。每次调用
call
函数时,都会创建一个新函数,其上下文会绑定现有的
内容
变量。
mouseover
处理程序与其中存储的名称之间的关系为1-1。它也可能是一个输入错误:将
内容
内容
进行比较。