如何注册一个onclick事件,以便它知道从哪个对象调用它

How to register an onclick event so it knows the object it is called from?

本文关键字:调用 对象 事件 注册 何注册 一个 onclick      更新时间:2023-09-26

我有一些简单的HTML &Javascript代码:

<span id="test">Hej</span>
function Hello(el)
{
    var el = document.getElementById('test');
    this.test = function(fun)
    {
        el.addEventListener('click', function(e)
        {
            fun(e);
        }, false); 
    }
}   
var hello = new Hello;
hello.test(function()
{
    console.log(this);
});

我想在console.log()中使用"this",但我希望它引用hello的实例。如何更改Hello的定义?

您可以使用Function#call,它允许您将this绑定到您想要的任何内容:

function Hello(el)
{
    var el = document.getElementById('test');
    var that = this;
    this.test = function(fun)
    {
        el.addEventListener('click', function(e)
        {
            fun.call(that, e);
        }, false); 
    }
}

在你的这个。测试功能替换:

fun(e);

:

fun.call(that, e);

并在事件侦听器之前添加以下内容:

var that = this;

您需要将其传递给传递的函数。通过在指定的侦听器函数中使用this关键字,方法addEventListener已经为您提供了对调用元素的访问。所以为了让这个对象进入你的"fun"函数,它需要作为一个变量传递。

function Hello(el)
{
    var el = document.getElementById('test');
    this.test = function(fun)
    {
        el.addEventListener('click', function(e)
        {
            fun(e, this);   // Adding the parameters to pass
        }, false); 
    }
}   
var hello = new Hello();
hello.test(function(event, el)  // The passed function should be ready to receive it
{
    alert(el.innerText);  
});

我用这把小提琴测试了一下。

编辑:不确定我第一次完全阅读了这个问题,但是如果你想从函数内访问Hello,你需要从你的"类定义"中提供它的实例。

function Hello(el)
{
    var self = this;
    var el = document.getElementById('test');
    this.test = function(fun)
    {
        el.addEventListener('click', function(e)
        {
            fun(e, self);   // Adding the parameters to pass
        }, false); 
    }
    this.someProperty = "to test the value";
}   
var hello = new Hello();
hello.test(function(event, obj)  // The passed function should be ready to receive it
{
    alert(obj.someProperty);  
});

我用这个提琴更新测试了第二个版本