0

这是使用多个 jQuery 脚本的正确方法吗?有些在同一个 .js 文件中,但是,即使有多个 .js 文件,似乎我能让它们同时工作的唯一方法是jQuery.noConflict()专门为每个文件声明一个变量,然后替换所有$具有该变量的实例。

这不可能是正确/最好的方法:不是吗?

我在下面提供了一个示例,一切正常,但这对我来说似乎不是“正确”的方式。

HTML:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="/js/jquery-1.8.2.min.js"><\/script>')</script>
<script src="/js/test.js"></script>
<script src="/js/shareit.js"></script>
<script>var $share = jQuery.noConflict();$share(document).ready(function(){$share('.sharer').sharer();});</script>

test.js 是:

/*faq stuff*/
var $zfaqs = jQuery.noConflict();
$zfaqs(document).ready(function () {    
$zfaqs('.faq dd').hide(); // Hide all DDs inside .faqs
$zfaqs('.faq dt').click(function(){$zfaqs(this).toggleClass('active')}); // add/remove active class on click
$zfaqs('.faq dt').click(function(){$zfaqs(this).next().slideToggle('fast')}); // toggle answer
});

/*new window link*/
var $zopen = jQuery.noConflict();
$zopen(document).ready(function() {
$zopen("a[data-window='external']").on('click', function() {
    window.open($zopen(this).attr('href')); 
    return false; 
});
});

/*fading text*/
var $zfader = jQuery.noConflict();
$zfader(document).ready(function(){
$zfader('.fadethis .fade');
    setInterval(function(){
        $zfader('.fadethis .fade').filter(':visible').fadeOut(2000,function(){
            if($zfader(this).next('.fade').size()){
                $zfader(this).next().fadeIn(1000);
            }
            else{
                $zfader('.fadethis .fade').eq(0).fadeIn(1000);
            }
        });
    },10000);   
});

编辑:

好的,我已经改成以下了。仍然有点困惑,但我到了那里。我知道使用 $(document).ready(function() { 基本上说等到页面加载然后运行代码 - 对吗?话虽如此,我已经进行了以下更改。

在 test.js 中,我将所有代码包装在一个 document.ready 中并对其进行了清理。

现在大家怎么看?现在这是为了纠正标准吗?

HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="/js/jquery-1.8.2.min.js"><\/script>')</script>
<script src="/js/test.js"></script>

<script src="/js/jquery.colormodal-min.js"></script>
<script>$(document).ready(function(){$("a[data-modal^='gss']").each(function(){$(this).colormodal({rel:$(this).attr('data-modal')});});$("a[data-modal='ss']").colormodal({rel: 'nofollow'});$("a[data-modal='no']").colormodal({title: ' ',rel: 'nofollow'})});</script>

<script src="/js/shareit.js"></script>
<script>$(document).ready(function(){$('.sharer').sharer();});</script>

test.js

/*twitter stuff*/
$(document).ready(function() {
$.getJSON('http://api.twitter.com/1/statuses/user_timeline/testing.json?count=1&callback=?', function(tweets){
$("#twitter").html(tz_format_twitter(tweets));
});

function tz_format_twitter(twitters) {
var statusHTML = [];
for (var i=0; i<twitters.length; i++){
var username = twitters[i].user.screen_name;
var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
  return '<a href="'+url+'">'+url+'</a>';
}).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
  return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
});
statusHTML.push('<span>'+status+'</span> <br/><b><a href="http://twitter.com/'+username+'/statuses/'+twitters[i].id_str+'">'+relative_time(twitters[i].created_at)+'</a></b>');
}
return statusHTML.join('');
}

function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);

if (delta < 60) {
return 'less than a minute ago';
} else if(delta < 120) {
return 'about a minute ago';
} else if(delta < (60*60)) {
return (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (120*60)) {
return 'about an hour ago';
} else if(delta < (24*60*60)) {
return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
return '1 day ago';
} else {
return (parseInt(delta / 86400)).toString() + ' days ago';
}
}

/*faq stuff*/   
$('.faq dd').hide(); // Hide all DDs inside .faqs
$('.faq dt').click(function(){$(this).toggleClass('active')}); // add/remove active class on click
$('.faq dt').click(function(){$(this).next().slideToggle('fast')}); // toggle answer

/*new window link*/
$("a[data-window='external']").on('click', function() {
    window.open($(this).attr('href')); 
    return false; 
});

/*fading text*/
setInterval(function(){
    $('.fadethis .fade').filter(':visible').fadeOut(2000,function(){
        if($(this).next('.fade').size()){
            $(this).next().fadeIn(1000);
        }
        else{
            $('.fadethis .fade').eq(0).fadeIn(1000);
        }
    });
},10000);

/*end document ready stuff*/
});
4

2 回答 2

0

Try not using noConflict() at all, and to not have more than one $(function(){ per location such as

<script>
  $(function(){
    $('.sharer').sharer();
  });
</script>

and

/*faq stuff*/

$(function(){   
  $('.faq dd').hide(); // Hide all DDs inside .faqs
  $('.faq dt').click(function(){$(this).toggleClass('active')}); // add/remove active class on click
  $('.faq dt').click(function(){$s(this).next().slideToggle('fast')}); // toggle answer


  /*new window link*/

  $("a[data-window='external']").on('click', function() {
    window.open($(this).attr('href')); 
    return false; 
  });


  /*fading text*/
  $('.fadethis .fade');  //(not sure what the purpose of this line is)
  setInterval(function(){
    $('.fadethis .fade').filter(':visible').fadeOut(2000,function(){
      if($(this).next('.fade').size()){
        $(this).next().fadeIn(1000);
      }
      else{
        $('.fadethis .fade').eq(0).fadeIn(1000);
      }
    });
  },10000); 
});
于 2013-01-19T08:40:10.083 回答
0

Let's consider:

console.log($); // Will be defined as a jQuery() shorthand
jQuery.noConflict();
console.log($); // Will be undefined

What happens is that jQuery will automatically "take" the $ function shorthand from the global scope, ie, window.$ will become shorthand for window.jQuery.

So, when we call jQuery.noConflict() we are primarily releasing window.$ back to the wild, in case it conflicts with another framework or library which also uses it (there are several others, MooTools is one).

So the following:

var $zfaqs = jQuery.noConflict();
$zfaqs(document).ready(function () { 
    ...
});

var $zopen = jQuery.noConflict();
$zopen(document).ready(function() {
    ...
});

var $zfader = jQuery.noConflict();
$zfader(document).ready(function(){
    ...
});

You're simply releasing (over and over) $ and then creating a new global reference to jQuery to use within that block that follows. $zfaqs should work every time. Unless they are included in a different order each time or whatnot.

As far as what your code is attempting to do, you could accomplish it without the global returned reference to jQuery that jQuery.noConflict() returns. For instance:

jQuery(document).ready(function ($) {
    $('#jQuery-ready').click(function () {
        console.log(this.id);
    });
});

jQuery(function ($) {
    $('#jQuery-only').click(function () {
        console.log(this.id);
    });
});

(function ($) {
    $(document).ready(function ($) {
        $('#Function-initializer').click(function () {
            console.log(this.id);
        });
    });
})(jQuery);

http://jsfiddle.net/userdude/D6ANv/1

And I do not have to do anything like var $jjq = jQuery.noConflict() globally and then reference those within my onDOMReady handlers, I can simply continue to use $ shorthand within those scopes, as long as I am not then trying to use another global $ that is not jQuery.

于 2013-01-19T08:42:30.327 回答