2014-10-27 47 views
10

我想鏈接HTML文檔中的Social FloatingShare jQuery插件。我試圖鏈接這個jQuery插件,但調用插件功能floatingShare()不工作,因爲我例外。如何鏈接html文檔中的jQuery插件

我有兩個問題:

  1. 如何把我的HTML文檔中jQuery的聯繫呢?
  2. 我在代碼中犯了什麼錯誤?

我的源代碼:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml"> 
 
<head> 
 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
 
    <title>Jquery Plugin</title> 
 
    <style> 
 
     body { margin: 0px; padding: 0px; background: #ccc; } 
 
     .container { height: 500px; width: 1000px; margin: 0px auto; padding: 0px; } 
 
    </style> 
 
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.1.0/css/font-awesome.min.css"> 
 
</head> 
 
<body> 
 
<div class="container"> 
 
    <script type="text/javascript"> 
 
     $(function(){ 
 
      $("body").floatingShare(); 
 
     }); 
 
    </script> 
 
</div> 
 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<script src="js/jquery.floating-share.js" type="text/javascript"></script> 
 
</body> 
 
</html>

+0

創建jsfiddel你https://jsfiddle.net/jalayoza/gd0grwpt/ – 2017-06-09 06:34:53

回答

10

您需要包括jQuery插件使用前,因爲所有的jQuery或jQuery的功能應該是使用前可用,所以更改jQuery庫和腳本序列如下所示 -

注意 - 將腳本標記直接保存到<body><head>標記中而不是其他任何html元素是一種很好的做法。

<body> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
<script src="js/jquery.floating-share.js" type="text/javascript"></script> 
<script type="text/javascript"> 
    $(function(){ 
    $("body").floatingShare(); 
    }); 
</script> 
<div class="container"> 

</div> 

</body> 
6

包括所有.js文件在Body塊到底是裝載表演一個很好的做法。然後,在完全加載頁面後,您必須確保從引用中調用任何JavaScript函數。

兩個常用的選項我通常選擇:

選項1。在Head中包含jQuery庫,並將所有其他.js文件保留在Body塊的末尾。在你的情況下,相關的JavaScript代碼的部分應爲:

<head> 
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
    </head> 
    <body> 
     <div class="container"> 
      <script type="text/javascript"> 
       $(document).ready(function(){ 
        $("body").floatingShare(); 
       }); 
      </script> 
     </div> 
     <script src="js/jquery.floating-share.js" type="text/javascript"></script> 
    </body> 

選項2。將所有.js文件保留在Body塊的末尾,然後在JavaScript中執行$(document).ready()而不是使用jQuery庫。據jQuery的資源,相當於純JavaScript實現的$(document).ready()是:

var ready = (function(){  

     var readyList, 
      DOMContentLoaded, 
      class2type = {}; 
      class2type["[object Boolean]"] = "boolean"; 
      class2type["[object Number]"] = "number"; 
      class2type["[object String]"] = "string"; 
      class2type["[object Function]"] = "function"; 
      class2type["[object Array]"] = "array"; 
      class2type["[object Date]"] = "date"; 
      class2type["[object RegExp]"] = "regexp"; 
      class2type["[object Object]"] = "object"; 

     var ReadyObj = { 
      // Is the DOM ready to be used? Set to true once it occurs. 
      isReady: false, 
      // A counter to track how many items to wait for before 
      // the ready event fires. See #6781 
      readyWait: 1, 
      // Hold (or release) the ready event 
      holdReady: function(hold) { 
       if (hold) { 
        ReadyObj.readyWait++; 
       } else { 
        ReadyObj.ready(true); 
       } 
      }, 
      // Handle when the DOM is ready 
      ready: function(wait) { 
       // Either a released hold or an DOMready/load event and not yet ready 
       if ((wait === true && !--ReadyObj.readyWait) || (wait !== true && !ReadyObj.isReady)) { 
        // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). 
        if (!document.body) { 
         return setTimeout(ReadyObj.ready, 1); 
        } 

        // Remember that the DOM is ready 
        ReadyObj.isReady = true; 
        // If a normal DOM Ready event fired, decrement, and wait if need be 
        if (wait !== true && --ReadyObj.readyWait > 0) { 
         return; 
        } 
        // If there are functions bound, to execute 
        readyList.resolveWith(document, [ ReadyObj ]); 

        // Trigger any bound ready events 
        //if (ReadyObj.fn.trigger) { 
        // ReadyObj(document).trigger("ready").unbind("ready"); 
        //} 
       } 
      }, 
      bindReady: function() { 
       if (readyList) { 
        return; 
       } 
       readyList = ReadyObj._Deferred(); 

       // Catch cases where $(document).ready() is called after the 
       // browser event has already occurred. 
       if (document.readyState === "complete") { 
        // Handle it asynchronously to allow scripts the opportunity to delay ready 
        return setTimeout(ReadyObj.ready, 1); 
       } 

       // Mozilla, Opera and webkit nightlies currently support this event 
       if (document.addEventListener) { 
        // Use the handy event callback 
        document.addEventListener("DOMContentLoaded", DOMContentLoaded, false); 
        // A fallback to window.onload, that will always work 
        window.addEventListener("load", ReadyObj.ready, false); 

       // If IE event model is used 
       } else if (document.attachEvent) { 
        // ensure firing before onload, 
        // maybe late but safe also for iframes 
        document.attachEvent("onreadystatechange", DOMContentLoaded); 

        // A fallback to window.onload, that will always work 
        window.attachEvent("onload", ReadyObj.ready); 

        // If IE and not a frame 
        // continually check to see if the document is ready 
        var toplevel = false; 

        try { 
         toplevel = window.frameElement == null; 
        } catch(e) {} 

        if (document.documentElement.doScroll && toplevel) { 
         doScrollCheck(); 
        } 
       } 
      }, 
      _Deferred: function() { 
       var // callbacks list 
        callbacks = [], 
        // stored [ context , args ] 
        fired, 
        // to avoid firing when already doing so 
        firing, 
        // flag to know if the deferred has been cancelled 
        cancelled, 
        // the deferred itself 
        deferred = { 

         // done(f1, f2, ...) 
         done: function() { 
          if (!cancelled) { 
           var args = arguments, 
            i, 
            length, 
            elem, 
            type, 
            _fired; 
           if (fired) { 
            _fired = fired; 
            fired = 0; 
           } 
           for (i = 0, length = args.length; i < length; i++) { 
            elem = args[ i ]; 
            type = ReadyObj.type(elem); 
            if (type === "array") { 
             deferred.done.apply(deferred, elem); 
            } else if (type === "function") { 
             callbacks.push(elem); 
            } 
           } 
           if (_fired) { 
            deferred.resolveWith(_fired[ 0 ], _fired[ 1 ]); 
           } 
          } 
          return this; 
         }, 

         // resolve with given context and args 
         resolveWith: function(context, args) { 
          if (!cancelled && !fired && !firing) { 
           // make sure args are available (#8421) 
           args = args || []; 
           firing = 1; 
           try { 
            while(callbacks[ 0 ]) { 
             callbacks.shift().apply(context, args);//shifts a callback, and applies it to document 
            } 
           } 
           finally { 
            fired = [ context, args ]; 
            firing = 0; 
           } 
          } 
          return this; 
         }, 

         // resolve with this as context and given arguments 
         resolve: function() { 
          deferred.resolveWith(this, arguments); 
          return this; 
         }, 

         // Has this deferred been resolved? 
         isResolved: function() { 
          return !!(firing || fired); 
         }, 

         // Cancel 
         cancel: function() { 
          cancelled = 1; 
          callbacks = []; 
          return this; 
         } 
        }; 

       return deferred; 
      }, 
      type: function(obj) { 
       return obj == null ? 
        String(obj) : 
        class2type[ Object.prototype.toString.call(obj) ] || "object"; 
      } 
     } 
     // The DOM ready check for Internet Explorer 
     function doScrollCheck() { 
      if (ReadyObj.isReady) { 
       return; 
      } 

      try { 
       // If IE is used, use the trick by Diego Perini 
       // http://javascript.nwbox.com/IEContentLoaded/ 
       document.documentElement.doScroll("left"); 
      } catch(e) { 
       setTimeout(doScrollCheck, 1); 
       return; 
      } 

      // and execute any waiting functions 
      ReadyObj.ready(); 
     } 
     // Cleanup functions for the document ready method 
     if (document.addEventListener) { 
      DOMContentLoaded = function() { 
       document.removeEventListener("DOMContentLoaded", DOMContentLoaded, false); 
       ReadyObj.ready(); 
      }; 

     } else if (document.attachEvent) { 
      DOMContentLoaded = function() { 
       // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). 
       if (document.readyState === "complete") { 
        document.detachEvent("onreadystatechange", DOMContentLoaded); 
        ReadyObj.ready(); 
       } 
      }; 
     } 
     function ready(fn) { 
      // Attach the listeners 
      ReadyObj.bindReady(); 

      var type = ReadyObj.type(fn); 

      // Add the callback 
      readyList.done(fn);//readyList is result of _Deferred() 
     } 
     return ready; 
     })(); 

然後,你可以用它喜歡:

ready(function(){ 
     $("body").floatingShare(); // Assuming jQuery Lib has been included as well 
    }); 

到目前爲止,我認爲選擇1應該是比較容易接受。

4

在您的代碼中存在代碼序列問題。根據jQuery代碼序列,您必須首先在您的文檔中包含jQuery,然後按照上面的回答@Bhushan Kawadkar所建議的所有自定義函數。

如果你仍然想添加你的函數在你添加它的主體,那麼你可以在文檔e的<head>中包含jQuery。g

<html> 
<head> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
    <script src="http://www.jqueryscript.net/demo/jQuery-Plugin-For-Horizontal-Floating-Social-Share-Bar/js/jquery.floating-share.js" type="text/javascript"></script> 
</head> 
<body> 
<div class="container"> 
    <script type="text/javascript"> 
$(function(){ 
$("body").floatingShare(); 
}); 
</script> 
</div> 
</body> 

而你的插件將開始工作。

不知何故,建議在腳註中添加腳本(js)以改善頁面的渲染時間。

這是一個現場演示給你。

http://codepen.io/anon/pen/AIEnl

+1

它現在運作良好:)謝謝@Jamil艾哈邁德 – 2014-11-03 03:13:26

+1

@RaoAsifRaza我很樂意幫助你。請將其標記爲已接受的答案。 – 2014-11-04 09:02:34

+0

親愛的@Jamil我是新的** stackoverflow **,我找不到選項,我選擇這是_accepted_ :(如果你幫助**引用**,所以在評論中分享鏈接,再次高級謝謝你的幫助:) :) – 2014-11-05 01:42:32