簡體   English   中英

Javascript動態加載jQuery庫

[英]Javascript loading jQuery library dynamically

為什么需要兩次單擊按鈕才能使此jQuery代碼正常工作? 瀏覽器將加載此文件,並在頂部加載腳本標簽。 但是此代碼僅在單擊2次后有效。

 function j1() { $("button").click(function() { $("p").hide(); }); } function load1() { var target = document.getElementsByTagName("head"); var newScript = document.createElement("script"); var url = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"; newScript.src = url; target[0].appendChild(newScript); newScript = document.createElement("script"); url = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"; newScript.src = url; target[0].insertBefore(newScript, target[0].firstChild); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!DOCTYPE html> <html> <head> </head> <body onload="load1();"> <h2>This is a heading</h2> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <button onclick="j1();">Click me</button> </body> </html> 

.click()調用注冊一個新的Click偵聽器。 因此,用戶按下按鈕一次以注冊單擊偵聽器,然后再次按下按鈕以隱藏段落。

相反,只需刪除onclick標記,然后使用.click()偵聽器,反之亦然。

 function load1() { var target = document.getElementsByTagName("head"); var newScript = document.createElement("script"); var url = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"; newScript.src = url; target[0].appendChild(newScript); newScript = document.createElement("script"); url = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"; newScript.src = url; target[0].insertBefore(newScript, target[0].firstChild); $("button").click(function() { $("p").hide(); }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!DOCTYPE html> <html> <head> </head> <body onload="load1();"> <h2>This is a heading</h2> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <button>Click me</button> </body> </html> 

我正在為這個問題添加一些細節...因此,如您在下面看到的那樣,我的小js文件已加載,並且簡單功能在第一次單擊時效果良好...這帶回了原始問題,為什么JQuery在以下情況下表現不同通過Js代碼加載?

  function load2()
    {
        var target = document.getElementsByTagName("head");

    var newScript = document.createElement("script");
    var url = "js_libs/f1.js";
    newScript.src = url; 
    target[0].appendChild(newScript);
}




  <body onload="load1(); load2();" >


   <button onclick="f1();">Click me too</button>

找到此問題的解決方案Stackoverflow問題...

在此處輸入鏈接說明

這是解決問題的代碼。

<script type='text/javascript'>
runScript();

function runScript() 
{
// Script that does something and depends on jQuery being there.
if( window.$ ) 
{
// do your action that depends on jQuery.
} 
else 
{
// wait 50 milliseconds and try again.
window.setTimeout( runScript, 50 );
}
}
</script>

暫無
暫無

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

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