我已经在我的网站中实现了以下代码(随机/随机排序divs顺序):

function shuffle(array) {
  var currentIndex = array.length
    , temporaryValue
    , randomIndex
    ;


  while (0 !== currentIndex) {


    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

$.fn.randomize = function (childElem) {

    return this.each(function () {
        var $this = $(this);
        var elems = shuffle($(childElem));
        $this.remove(childElem);
        for (var i = 0; i < elems.length; i++)
            $this.append(elems[i]);
    });
}

jQuery(function($){
    $("div.container").randomize("div.random");
});


但是由于与其他脚本冲突而无法正常工作,我认为$ .noConflict();是这种情况。

这是小提琴,http://jsfiddle.net/7L4gu/我很努力地自己解决问题,非常感谢您的帮助!

最佳答案

由于noConflict(),一旦使用它,$就不再引用jQuery。麻烦的是,一旦您调用$noConflict()的值就不确定了,因此表达式$.fn将失败。

广泛使用的解决方案是使用IIFE这样的

(function ($) {
    $.fn.randomize = function (childElem) {
        return this.each(function () {
            var $this = $(this);
            var elems = shuffle($(childElem));
            $this.remove(childElem);
            for (var i = 0; i < elems.length; i++)
            $this.append(elems[i]);
        });
    }
})(jQuery)


演示:Fiddle

在这种情况下,在IIFE方法内部,我们将接收jQuery对象作为参数,并将其命名为局部范围变量$,以便我们可以在插件中使用较短的形式。

关于javascript - jQuery $ .noConflict();问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21923823/

10-09 21:57