我在我的视图页面中有这个:
<input type="checkbox" id="toggle_SITEID" name="@@toggle_SITEID" onclick="toggle_SITEID(this)" /> New <br />然后在我的js文件中我有这个:
toggle_SITEID = function (chk) { // something }然后我点击复选框,“某事”将无法运行。 我检查firebug控制台的错误信息是:
toggle_SITEID不是一个函数
那为什么呢?
I have this in my view page:
<input type="checkbox" id="toggle_SITEID" name="@@toggle_SITEID" onclick="toggle_SITEID(this)" /> New <br />then in my js file I have this:
toggle_SITEID = function (chk) { // something }and then I click checkbox, "something" won't run. I check in firebug console the error message was:
toggle_SITEID is not a function
So why is it?
最满意答案
这个错误可能有几个原因:
您没有在HTML文件中引用该脚本。
该函数未在全局范围内声明,而是在内部范围中声明。 全球范围 - 工作演示 内在范围 - 非工作演示
有一个元素的id与函数名称( toggle_SITEID )相同。 在Internet Explorer中,使用元素的id是document.getElementById()的快捷方式。 使用var声明中断链接。
可能出现的另一个问题是,当您有一个内联处理程序试图使用干扰内联处理程序的唯一作用域链的全局变量时。 这种情况发生在全球......
与具有处理程序的元素上的任何属性具有相同的名称,或 与document任何属性具有相同的名称由于内联处理程序的作用域链具有元素本身以及作为变量对象注入作用域链的document ,因此这些对象上的任何属性在访问全局变量时都会发生干扰。
例如,给定这个元素: <a onclick="foo();">click me</a> ,我们可以成功调用全局foo() 除非我们做过像document.foo = "bar"这样的事情。 由于document是作为范围链中的变量对象注入的,因此document.foo现在会影响全局foo 。
元素本身也是如此。 如果我们在调用全局函数之前将foo属性添加到元素,那么该属性将影响全局。 <a onclick="this.foo = 'bar'; foo();">click me</a>
There could be couple of reasons for this error:
You didn't reference the script in the HTML file.
The function isn't declared in the global scope but in an inner scope. global scope- WORKING DEMO inner scope - NON WORKING DEMO
There is an element whose id is the same as the function name(toggle_SITEID). In Internet Explorer, using an element's id is a shortcut for document.getElementById(). Break the link by using a var declaration.
Another issue that can arise is when you have an inline handler that tries to use a global variable that interferes with the unique scope chain of inline handlers. That happens when the global...
has the same name as any property on the element with the handler, or has the same name as any property on the documentSince the scope chain of an inline handler has the element itself, as well as the document, injected into the scope chain as variable objects, any property on those objects will interfere when accessing global variables.
For example, given this element: <a onclick="foo();">click me</a>, we can successfully invoke the global foo() unless we've done something like document.foo = "bar". Since the document is injected as a variable object in the scope chain, the document.foo now shadows the global foo.
Same goes with the element itself. If we add the foo property to the element before invoking the global function, that property will shadow the global. <a onclick="this.foo = 'bar'; foo();">click me</a>
更多推荐
发布评论