【问题标题】:calling jquery method cannot find the plugin调用jquery方法找不到插件
【发布时间】:2012-01-19 07:30:56
【问题描述】:

我的 html 文件中有这段代码:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="http://www.anotherdomain.com/javascript.js" type="text/javascript"></script>
<script type="text/javascript">
  $.keyCode({code: "google"});
</script>

http://www.anotherdomain.com/javascript.js 中定义了这个函数:

$(document).ready(function(){
    jQuery.keyCode = function(params){
        params = $.extend( {code: "grid"}, params); 
        var key_code = params.code;
        $("html").live("keypress", function(e){
            if (cookieIsSet() == false){
              check_key_pressed(key_code, e);
            } 
        });
    };
});

应用找不到$.keyCode 方法。

【问题讨论】:

    标签: javascript jquery plugins jquery-plugins


    【解决方案1】:

    您对jQuery.keyCode 的定义只有在文档准备好后才可用。而$.keyCode({code: "google"});在它之前执行,从而导致未定义的问题。

    要修复它,您应该删除 $(document).ready 包装器。

    【讨论】:

    • 好的,但是.live 事件需要在document.ready 中,同时仍然可以从插件访问key_code 参数。我该怎么做?
    • 虽然你的理由是对的,但你对补救措施是错误的。删除文档就绪包装器是错误的做法。 @JustinMeltzer:只需将您的$.keyCode({code: "google"}); 放入它自己的文档准备好的包装器中。 (另请参阅 SO 上的Order of execution of jquery document ready。)
    • @JustinMeltzer 只需将document.ready 包裹在live 部分周围。顺便说一句,你真的不应该在jQuery 1.7 之后使用live,而是使用on
    【解决方案2】:

    你有没有尝试过这样的事情:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
    <script src="http://www.anotherdomain.com/javascript.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function() {
            $.keyCode({code: "google"});
        });
    </script>
    

    或者你甚至可以使用这个,它会在以后触发:

    $(window).load(function() {...});
    

    【讨论】:

      猜你喜欢
      • 2011-11-24
      • 1970-01-01
      • 1970-01-01
      • 2013-08-08
      • 1970-01-01
      • 2013-08-24
      • 2011-11-17
      • 2012-02-12
      • 1970-01-01
      相关资源
      最近更新 更多