javascript函数名称不能设置为点击? [英] javascript function name cannot set as click?
问题描述
下面是我的代码,它不起作用。将click()重命名为click1()后,它会起作用,为什么?
< head>
< title>< / title>
< script type =text / javascript>
函数click(){
document.getElementById(content)。innerHTML =abc;
}
< / script>
< / head>
< body>
< div id =content>< / div>
< / body>
< / html>
onfoo处理程序属性的字符串值被解释作为处理函数的主体。换句话说,就好像该属性的字符串值被传递给 new Function(event,str)
,其结果是使用的处理函数。
此外,函数的词法范围建立如下,取自HTML5规范(我仅在浏览器行为的全面描述方面进行了咨询):
词法环境范围
*让范围成为NewObjectEnvironment(元素的Document,全局环境)。
*如果元素具有表单所有者,那么让成为NewObjectEnvironment的结果元素的表单所有者 Scope )。
*设置 Scope 是NewObjectEnvironment(元素的对象, Scope )的结果。
因此,就好像有多达两个嵌套的与块隐式地缠绕代码。因此,在这种情况下,效果是调用它:
var handler = new Function(event,with(this ){click();});
因为在< $< ; button>
,该函数是处理函数调用的函数,而不是由脚本标记建立的全局函数。如果onclick属性设置为window.click();那么该页面可以正常工作。
Below is my code and it doesn't work. After I rename the "click()" to "click1()" it works, why?
<html>
<head>
<title></title>
<script type="text/javascript">
function click() {
document.getElementById("content").innerHTML = "abc";
}
</script>
</head>
<body>
<button onclick="click()">try it</button><br />
<div id="content"></div>
</body>
</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.
这篇关于javascript函数名称不能设置为点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!