2014-07-09 46 views
0

后,按钮被从html页面中删除任何人都可以解释为什么这段代码将在FF和Chrome中点击后删除buton吗? IE会显示警报。执行函数名称为remove()

<html> 
<head> 
<script> 
function remove() 
{ 
alert('test'); 
} 

</script> 
</head> 
<body> 
<input type="button" onclick="remove();" value="Remove"/> 
</body> 
</html> 
+3

请勿在JavaScript方法或事件之后命名函数 – j08691

+0

[请勿使用内联事件处理程序](http://stackoverflow.com/a/21975639/218196)或者至少知道你在做什么。[DOM节点有一个'remove'方法](https://developer.mozilla.org/en-US/docs/Web/API/ChildNode.remove)和这是什么被调用,而不是你的功能 –

+1

好发现@ j08691。 –

回答

1

因为javascript有一个remove方法。命名你的功能abcd,它很好:

<html> 
<head> 
<script> 
function abcd() 
{ 
alert('test'); 
} 

</script> 
</head> 
<body> 
<input type="button" onclick="abcd();" value="Remove"/> 
</body> 
</html> 
+0

“remove”在这里没有列为事件:https://developer.mozilla.org/en-US/docs/Web/Events。您有没有任何参考? –

+0

我也在看,我只看到了这个HTTPS://developer.mozilla。 org/en-US/docs/Web/API/ChildNode.remove – mplungjan

+0

抱歉,我的错,我会编辑 –

0

通常被认为是不好的做法,因为你是要求浏览器从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”)再次访问它)