Javascript 在外部js文件中从xhtml调用JQuery函数

Javascript 在外部js文件中从xhtml调用JQuery函数,javascript,jquery,html,function,Javascript,Jquery,Html,Function,我在外部js文件中定义了一个jquery函数: myJquery.js (function($) { $.fn.test = function (options) { //Extended default options var opts = $.extend({ chars: 0 }, options); ...doSomething... })(jQuery); 在xhtml中将

我在外部js文件中定义了一个jquery函数: myJquery.js

    (function($) {  
       $.fn.test = function (options) {  
           //Extended default options
           var opts = $.extend({
                  chars: 0
 }, options);
...doSomething...
})(jQuery);
在xhtml中将此文件包含为:

<script type="text/javascript" src="_/js/myJquery.js"/>
但是获取js时出错,表示找不到“test”函数。

您的测试函数的作用域是外部文件空间,而不是全局环境。如果您确定jQuery具有$wrapper命令,则在不使用$wrapper函数的情况下追加函数

编辑:虽然上述内容可能仍与其他相关。。。至少对于只显示带有}的警报来说,它确实可以正常工作:

包含的外部文件

第页:

<script type="text/javascript">
$(document).ready(function() {
      $("h1").each(function() {
              $(this).test({
                    chars:10
             });
       });
 });
</script>

我从myJquery.js中删除了函数$,从上面的myJquery.js代码片段中删除了第一行和最后一行,但仍然存在相同的问题。我正确理解你的建议了吗!!嗯,我甚至没有注意到,但是您缺少了一个用于关闭函数声明的花括号。
(function($) {
   $.fn.test = function (options) {
       //Extended default options
       var opts = $.extend({chars: 0}, options);
       alert('boo: '+opts.chars);
   }
})(jQuery);
<script type="text/javascript">
$(document).ready(function() {
      $("h1").each(function() {
              $(this).test({
                    chars:10
             });
       });
 });
</script>