簡體   English   中英

如何在外部.js文件中使用jquery?

[英]How to use jquery in a external .js file?

在我的網站上,有兩個文件:index.php,script.js當然,它在網站中要復雜得多,上面僅顯示了一部分。

在index.php中,有一個div元素

<div id="phb29" class="drag ph hour01">Testing</div>

在script.js(這是一個純javascipt文件)中,下面顯示了我要使用jquery函數.switchClass()(來自http://api.jqueryui.com/switchClass/ )來切換div元素類的部分。

//... other normal js codes

switchClassHour = function(){

    $(function (){       
            $( "#phb29" ).switchClass( "hour01", "hour03", 1000 );
                return false;
        });     
}

//other normal js codes...

我只想在調用switchClassHour()函數時調用該jquery,但未加載網頁(即$(document).ready(function(){...});)

我已經將源代碼包含在index.php中:

<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript" src="script.js"></script>

但是最后,當我觸發switchClassHour()時,chrome瀏覽器給我這個錯誤發生在$(function(){)行:

Uncaught TypeError: boolean is not a function 

我該怎么辦,謝謝!!!!! :) :)

function switchClassHour(){
    if(document.getElementById('jq')){
        //original switchClassHour() code. 
    }
    else{
        var jq = document.createElement('script');
        jq.src = "WHATEVER SOURCE YOU WANT TO LOAD FROM (PROBABLY GOOGLE)";
        jq.id = "jq";
        document.getElementsByTagName('head').item(0).appendNode(jq);
        //Original switchClassHour() code
   }
}

我不知道這是否一定能正常工作,因為我不知道您是否能夠足夠快地加載jQuery以隨后立即調用您的函數。 如果由於jQuery加載速度不夠快而導致此方法不起作用,那么我能看到的唯一結果就是增加了延遲,但這很丑陋。 老實說,如果您使用的是jQuery,我通常會在頁面的<head>中從Google正常加載它。 大多數人已經緩存​​了它。

變量toHour似乎沒有在switchClassHour函數中switchClassHour

嘗試這個

switchClassHour = function(){
/* `toHour` ? */
  if (window.jQuery) {
    /* $(function (){  */     
            $( "#phb29" ).switchClass( "hour01", "hour03", 1000 );
                /* `return false;` ? */
    /*    }); */
  };    
};
switchClassHour(); /* just noticed, is the function actually called ? */

編輯

嘗試這個

   switchClassHour = function(){
    /* `toHour` ? */
      if (window.jQuery) {
        /* $(function (){  */     
                console.log($.now())
                    /* `return false;` ? */
        /*    }); */
      };    
    };
    switchClassHour();

$.now()是否在控制台返回?

$是否可用於非jquery片段的其他部分?

另請參閱https://api.jquery.com/jQuery.noConflict/

編輯

嘗試這個

switchClassHour = function() {
  jQuery.noConflict();
    (function( $ ) {
     console.log($.now(), jQuery.now())
  })(jQuery);
};switchClassHour();

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM