按钮在执行名为remove()的函数后从html页面中删除

Button is removed from html page after executing function which name is remove()

本文关键字:html 删除 函数 执行 remove 按钮      更新时间:2023-09-26

谁能解释为什么这段代码将删除按钮后点击FF和Chrome?IE将显示一个警告。

<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>

不要使用内联事件处理程序,或者至少知道自己在做什么。

问题是元素本身的属性在内联事件处理程序的范围内,DOM节点有一个remove方法*****。因此,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>

也不需要将其声明为窗口变量(全局),除非您想在函数中访问它。(但也可以通过document.getElementById("myButton")再次访问它)