2016-12-05 115 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(); 
    } 
});