2016-12-05 119 views
-1

我正在一個頁面,沒有在DOM引用的jquery。我需要使用一些jquery功能,所以我認爲最好的選擇是將jquery插入到現有的dom中。我從Load jQuery with Javascript and use jQueryHow to include jQuery dynamically in any website using pure javascript得到功能想法....這些解決方案似乎都不適合我。我仍然收到一個錯誤,無法識別jquery選擇器。動態加載jquery在普通的javascript

(function() { 
    function getScript(url, success) { 
     var script = document.createElement('script'); 
     script.src = url; 
     var head = document.getElementsByTagName('head')[0], 
      done = false; 
     // Attach handlers for all browsers 
     script.onload = script.onreadystatechange = function() { 
      if (!done && (!this.readyState 
       || this.readyState == 'loaded' 
       || this.readyState == 'complete')) { 
      done = true; 
      success(); 
      script.onload = script.onreadystatechange = null; 
      head.removeChild(script); 
      } 
     }; 
     head.appendChild(script); 
    } 
    getScript('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js',function() { 
     // Yay jQuery is ready \o/ 
    });       


    cards = $('div:first'); 
    $('body').empty().append(cards); 

    // Delete first and second child divs 

    first = $('div:first div:first'); 
    $('div:first div:first').css('position', '').css('left', '').css('z-index', '').css('height', '250px').remove(); 

    second = $('div:first div:first'); 
    $('div:first div:first').css('position', 'relative').css('left', '').css('z-index', '').remove(); 

    $('body').empty().append(first).append(second); 
    })(); 
+2

你應該把自己的代碼移到回調中,它說'// Yay ...'。只有這樣,你的代碼纔會在加載jQuery之後運行。 –

+0

wel; l多數民衆贊成在尷尬......隨時回答和不好接受 –

+0

腳本元素沒有這樣的屬性「onreadystatechange」,我認爲這是誤導性的信息,只是「onload」就足夠了。這裏來自Chris G的回答是可以接受的。這是同一個https://plnkr.co/edit/WYV7PQDX9wJTjnVfQENa?p=preview –

回答

1

你應該將你自己的代碼步入回調,到那裏說://耶....只有這樣,你的代碼運行 jQuery的加載後。

getScript('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js', function() { 
    // Yay jQuery is ready \o/ 

    $('body').empty().append($('div:first')); 
    // Delete first and second child divs 
    for (var i = 0; i < 2; i++) { 
     $('div:first div:first').remove(); 
    } 
});