gpt4 book ai didi

JavaScript POO : it is possible to put a object method in an onclick?

转载 作者:行者123 更新时间:2023-12-03 08:51:00 25 4
gpt4 key购买 nike

我想在 onclick 中放置一个对象方法,但我的代码不起作用。

这里是代码,非常简单:

<script type="text/javascript">

//The constructor :
function Foo()
{
/*Create a div element and add it to the document :*/
div_element = document.createElement("div");
document.body.insertBefore(div_element, null);

/*Create a method for hidding div element :*/
this.hide = function()
{
div_element.style.display = "none";
}

/*Insert button inside the div element. This button contains the method this.hide() in an onclick for hidding the div element :*/
div_element.innerHTML = '<input type="button" value="Hide" onclick="this.hide();">';
}

foo = new Foo();

</script>

但是按钮中的 this.hide() 方法不起作用。您可以尝试这里的代码: https://jsfiddle.net/0s5smd52/

你有什么想法吗?

提前致以诚挚的谢意

最佳答案

您的 hide() 函数的作用域为您的 Foo() 对象。如果您按照现在的方式将其添加到输入中,它将在全局范围内进行解释,并且 this.hide() 将有效地表示 window.hide(),不存在。

解决这个问题的方法是创建新的输入,设置 onclick 处理程序,然后将其添加到 DOM。

此外,在变量前面使用 var ,这样它们就不会污染全局范围。

function Foo()
{
var div_element = document.createElement('div');

this.hide = function()
{
div_element.style.display = 'none';
}

// create hide button
var btn = document.createElement('input');
btn.type = 'button';
btn.value = 'Hide';
btn.onclick = this.hide;

// add it to the div
div_element.appendChild(btn);

// add everything to the DOM
document.body.insertBefore(div_element, null);
}

foo = new Foo();

关于JavaScript POO : it is possible to put a object method in an onclick?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32671200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com