在原型存在的地方注入jQuery-noConflict()

| 我仅使用webkit。我需要将jQuery注入已经加载了原型的页面中。我正在使用此代码加载jQuery。 (您可以在控制台中尝试)
var s = document.createElement(\'script\');
s.setAttribute(\'src\', \'http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.js\');
s.setAttribute(\'type\', \'text/javascript\');
document.getElementsByTagName(\'head\')[0].appendChild(s);
我上面的代码出现错误。 如何在加载时使用noConflict()。如果在注入jquery脚本后放置以下代码,仍然会出现错误。
$(document).ready(function() {
  jQuery.noConflict();
  // my thing here
});
这也会引发错误:
jQuery.noConflict();
$(document).ready(function() {
  // my thing here
});
    
已邀请:
        尝试
var $j = jQuery.noConflict();
$j(document).ready(function() {
  // my thing here
});
然后,您可以将$ j用于任何jquery $     
        编辑:因为您正在从另一个脚本加载脚本,所以应将需要运行的
jQuery
代码放入脚本的加载事件的回调中:
var s = document.createElement(\'script\');
s.setAttribute(\'src\', \'http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.js\');
s.setAttribute(\'type\', \'text/javascript\');
document.getElementsByTagName(\'head\')[0].appendChild(s);

   // Place your code in an onload handler for the jQuery you\'re loading
s.onload = function() {

    jQuery.noConflict(); // release jQuery\'s hold on \"$\"

    jQuery(document).ready(function( $ ) {

      alert( $.fn.jquery );
   });
};
另一个解决方案是不使用这种加载jQuery的方法。只需对您的
<script>
元素进行硬编码,代码就会以预期的同步方式运行:
<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.js\" type=\"text/javascript\"></script>

<script type=\"text/javascript\">
    jQuery.noConflict(); // release jQuery\'s hold on \"$\"

      // do this with ready() -------v------ and the \"$\" will be available inside
    jQuery(document).ready(function( $ ) {

      // $ is safe for jQuery inside this .ready() callback
      alert( $.fn.jquery );
    });
</script>
原始答案: 做这个:
var s = document.createElement(\'script\');
s.setAttribute(\'src\', \'http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.js\');
s.setAttribute(\'type\', \'text/javascript\');
document.getElementsByTagName(\'head\')[0].appendChild(s);


jQuery.noConflict(); // release jQuery\'s hold on \"$\"

  // do this with ready() -------v------ and the \"$\" will be available inside
jQuery(document).ready(function( $ ) {

  // $ is safe for jQuery inside this .ready() callback
  alert( $.fn.jquery );
});
    
        $是jQuery(以及原型)的别名/快捷方式。 NoConflict基本上释放$快捷方式的控制权,因此一旦调用,其他库就可以控制它。尝试这个:
jQuery(document).ready(function() {
  // my thing here
});
    
        在这里,您先使用
$
,然后再使用
jQuery.noConflict()
,问题是在设置无冲突之前,您(错误地)假设ѭ10set是jQuery:
$(document).ready(function() {
  jQuery.noConflict();
  // my thing here
});
在这里,您做相反的事情。首先,您做了一些无冲突的事情,很好,但是随后继续使用
$
访问jQuery,它将不再起作用(由于as15ѭ调用的直接结果):
jQuery.noConflict();
$(document).ready(function() {
  // my thing here
});
结合您的两种努力,您将获得以下结果。我还在
.ready
行中添加了
$
,以便在
ready
函数中仍可以将
$
用作jQuery参考。
jQuery.noConflict(); // stops $ being associated with jQuery
jQuery(document).ready(function($) { // use long-hand jQuery object reference to call `ready()`
  // my thing here
});
    

要回复问题请先登录注册