存储'this'对象中的onclick属性

store the 'this' object in an onclick attribute

本文关键字:onclick 属性 this 存储 对象      更新时间:2023-09-26

我最终想要检索下面示例脚本的innerHTML (html将放在数据库中)。它还必须包括onclick事件。但是,在生成的HTML中没有可用的onclick事件。

<html>
</head>
<script>
function test() {
    this.goodbye="goodbye!";
    this.elem=document.createElement('div');
    this.elem.style.border='1px solid #888888';
    this.elem.textContent="hello";
    this.elem.style.cursor='pointer';
    var that=this;
    this.elem.onclick=function(){that.say_goodbye();}
    document.getElementsByTagName('body')[0].appendChild(this.elem);
}
test.prototype.say_goodbye=function(blockid) {
    this.elem.textContent=this.goodbye;
}
</script>
</head>
<body>
<script>var obj = new test();</script>
<a href="javascript:alert(obj.elem.outerHTML);">get html</a>
</body>
</html>

重要行如下:

this.elem.onclick=function(){that.say_goodbye();}

我尝试添加它作为属性,如:

this.elem.setAttribute('onclick',that.say_goodbye.bind(that));

但是它不起作用。当我点击给定代码中的链接时,浏览器会发出警告:

<div> onclick="function(){[native code]}" ..... </div>

在这种情况下,HTML现在有一个'onclick'事件,但包含'[native code]'作为动作。

谁知道如何使代码工作?

你得到这个的原因是属性值总是文本,你正试图把对象放入其中(函数是对象)。这种情况下你应该用这个。