jQuery里面的函数调用另一个函数= undefined?
我想在身体之前调用另一个function,但是如何?
系统显示错误undefined function myx
我只能在身体后添加代码。
jQuery(function($){ function myx() { alert("omg"); }; }); jQuery(document).ready(function($){ $("mytest").click(function(){ myx(); }); }); Check
该function超出范围。 您需要在jQuery回调之外定义函数。
Check
使用外部JavaScript,因此它被缓存到浏览器内存中,因此当您的客户端再次访问时,它将加载更快。 然后看看这个:
// wrapper is same as $(document).ready() with no-conflict jQuery(function($){ // should be defined once everything has loaded function myx(){ // never use alert except to test alert('OMG!'); } // passing a function name like a var is the same as Anonymous function $('#mytest').click(myx); }); // Ignoring outer wrapper to save indenting - indent everything further
重要的是myx
应该在所有内容加载后定义。
您不必这样做,但最佳做法是使用外部JavaScript并将标记放在
,同时设置
符合W3C标准。 另外,从技术上讲,如果你的
标签是在
中定义的,那么
document.body
可能不适用于某些旧版浏览器,因为HTML必须在JavaScript能够获取之前定义,这就是你使用匿名函数的原因在jQuery()
(与$(document).ready()或JavaScript onload Event相同)。 然后,您将获得带有JavaScript的HTML,因为这些元素可以上载。