Javascript 在执行名为remove()的函数后,按钮将从html页面中删除
有人能解释一下为什么这段代码会在点击FF和Chrome后删除buton吗?我将发出警报Javascript 在执行名为remove()的函数后,按钮将从html页面中删除,javascript,Javascript,有人能解释一下为什么这段代码会在点击FF和Chrome后删除buton吗?我将发出警报 <html> <head> <script> function remove() { alert('test'); } </script> </head> <body> <input type="button" onclick="remove();" value="Remove"/> </body> </h
<html>
<head>
<script>
function remove()
{
alert('test');
}
</script>
</head>
<body>
<input type="button" onclick="remove();" value="Remove"/>
</body>
</html>
函数删除()
{
警报(“测试”);
}
因为javascript有一个remove方法。将函数命名为abcd,这样就可以了:
<html>
<head>
<script>
function abcd()
{
alert('test');
}
</script>
</head>
<body>
<input type="button" onclick="abcd();" value="Remove"/>
</body>
</html>
函数abcd()
{
警报(“测试”);
}
或者至少知道你在做什么
问题是元素本身的属性在内联事件处理程序的作用域中,*****。因此remove()
相当于this.remove()
,即调用按钮的remove
方法
解决方案:
- 重命名你的函数
*:这是一个相对较新的API,IE尚不支持,因此它在IE中运行良好。使用内联事件处理程序通常被认为是不好的做法,因为您要求浏览器从html字符串解析javascript事件,更好的方法如下:
<html>
<head>
<script>
window.addEventListener("load",function(){
window.myButton = document.getElementById("myButton");
window.myButton.addEventListener("click",myButtonFunction);
});
function myButtonFunction()
{
alert('test');
}
</script>
</head>
<body>
<input id="myButton" type="button" value="Remove"/>
</body>
</html>
addEventListener(“加载”,函数(){
window.myButton=document.getElementById(“myButton”);
window.myButton.addEventListener(“单击”,myButton函数);
});
函数myButtonFunction()
{
警报(“测试”);
}
此外,您不需要将其声明为窗口变量(全局),除非您希望在函数中访问它。(但也可以通过document.getElementById(“myButton”)再次访问它)不要以JavaScript方法或事件命名函数。或者至少知道你在做什么。这就是被调用的函数,而不是你的函数。@FelixKling-谢谢。我以前看过它就知道这里有一个类似的问题。找到它花了一点功夫,但我的OCD现在感觉好多了。“删除”此处未列为事件:。您有任何参考资料吗?我也在查看。我只看到了此内容抱歉,我的不好,我将编辑