Below is my code and it doesn\'t work. After I rename the \"click()\" to \"click1()\" it works, why?
You should perhaps consider using jQuery to refactor your code:
<html>
<head>
<title></title>
</head>
<body>
<button id="button1">try it</button><br />
<div id="content"></div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#button1").click(function() {
$("#content").html("abc");
});
});
</script>
</body>
</html>
click is predefined event. You should not use predefined events.
click() is the inbuilt of javascript's button object.
click() a reserved name for a method used in HTML5 http://www.w3.org/TR/html5/webappapis.html
The string values of "onfoo" handler attributes are interpreted as the bodies of handler functions. In other words, it's as if the string value of the attribute is passed to new Function("event", str)
with the result being the handler function used.
Additionally, the lexical scope of the function is established as follows, taken from the HTML5 spec (which I consult only in its capacity of a comprehensive description of browser behavior):
Lexical Environment Scope
* Let Scope be the result of NewObjectEnvironment(the element's Document, the global environment).
* If the element has a form owner, let Scope be the result of NewObjectEnvironment(the element's form owner, Scope).
* Let Scope be the result of NewObjectEnvironment(the element's object, Scope).
Thus it's as if there are up to two nested with
blocks implicitly wrapped around the code. Thus in this case the effect is that of calling this:
var handler = new Function("event", "with (this) { click(); }");
Because there's a "click" method on the DOM element corresponding to the <button>
, that function is what's called by the handler, not the global one established by the script tag. If the "onclick" attribute is set to "window.click();" then the page works properly.
There's already a function called click, responsible for calling the event handler. By declaring another, you override the first, so the event doesn't work anymore.