jQuery Uncaught TypeError : [object Window] 개체의 '$'속성이 함수가 아닙니다.


92

모두 사전 번들로 제공되는 JS / CSS 양식 응용 프로그램을 다운로드했고 Wordpress에서 사용하려고합니다. 다음 코드가 있습니다.

$(document).ready(function () {


/*----------------------------------------------------------------------*/
/* Parse the data from an data-attribute of DOM Elements
/*----------------------------------------------------------------------*/


$.parseData = function (data, returnArray) {
    if (/^\[(.*)\]$/.test(data)) { //array
        data = data.substr(1, data.length - 2).split(',');
    }
    if (returnArray && !$.isArray(data) && data != null) {
        data = Array(data);
    }
    return data;
};

/*----------------------------------------------------------------------*/
/* Image Preloader
/* http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript
/*----------------------------------------------------------------------*/



// Arguments are image paths relative to the current page.
$.preload = function() {
    var cache = [],
        args_len = arguments.length;
    for (var i = args_len; i--;) {
        var cacheImage = document.createElement('img');
        cacheImage.src = arguments[i];
        cache.push(cacheImage);
    }
};


/*----------------------------------------------------------------------*/
/* fadeInSlide by revaxarts.com
/* Fades out a box and slide it up before it will get removed
/*----------------------------------------------------------------------*/


$.fn.fadeInSlide = function (speed, callback) {
    if ($.isFunction(speed)) callback = speed;
    if (!speed) speed = 200;
    if (!callback) callback = function () {};
    this.each(function () {

        var $this = $(this);
        $this.fadeTo(speed / 2, 1).slideDown(speed / 2, function () {
            callback();
        });
    });
    return this;
};


/*----------------------------------------------------------------------*/
/* fadeOutSlide by revaxarts.com
/* Fades out a box and slide it up before it will get removed
/*----------------------------------------------------------------------*/


$.fn.fadeOutSlide = function (speed, callback) {
    if ($.isFunction(speed)) callback = speed;
    if (!speed) speed = 200;
    if (!callback) callback = function () {};
    this.each(function () {

        var $this = $(this);
        $this.fadeTo(speed / 2, 0).slideUp(speed / 2, function () {
            $this.remove();
            callback();
        });
    });
    return this;
};

/*----------------------------------------------------------------------*/
/* textFadeOut by revaxarts.com
/* Fades out a box and slide it up before it will get removed
/*----------------------------------------------------------------------*/


$.fn.textFadeOut = function (text, delay, callback) {
    if (!text) return false;
    if ($.isFunction(delay)) callback = delay;
    if (!delay) delay = 2000;
    if (!callback) callback = function () {};
    this.each(function () {

        var $this = $(this);
        $this.stop().text(text).show().delay(delay).fadeOut(1000,function(){
            $this.text('').show();
            callback();
        })
    });
    return this;
};

/*----------------------------------------------------------------------*/
/* leadingZero by revaxarts.com
/* adds a leding zero if necessary
/*----------------------------------------------------------------------*/


$.leadingZero = function (value) {
    value = parseInt(value, 10);
    if(!isNaN(value)) {
        (value < 10) ? value = '0' + value : value;
    }
    return value;
};


});

Wordpress 충돌이 문제를 일으키지 않는다고 가정했기 때문에 마지막 브래킷을 다음과 같이 업데이트했습니다.

}, "jQuery");

그러나 여전히 동일한 오류가 발생합니다. 누구든지이 문제의 원인과 해결 방법을 알고 있습니까?

미리 감사드립니다!

답변:


260

이것은 구문 문제입니다. WordPress에 포함 된 jQuery 라이브러리는 "충돌 없음"모드로로드됩니다. 이는 WordPress에서로드 할 수있는 다른 자바 스크립트 라이브러리와의 호환성 문제를 방지하기위한 것입니다. "no-confict"모드에서는 $ 단축키를 사용할 수 없으며 더 긴 jQuery가 사용됩니다.

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

함수 호출 후 괄호 안에 $를 포함하면 코드 블록 내에서이 바로 가기를 사용할 수 있습니다.

자세한 내용은 WordPress Codex를 참조하십시오.


마지막에 "jQuery"를 풀어야한다는 점을 추가해야합니다
RedEyedMonster

3
당신은 생명의 은인입니다 !!! 3 일의 디버깅 후 이것이 내 문제에 대한 정확한 해결책이라는 것을 알았습니다. WordPress가 jQuery 파일을로드하고 있었지만 문서에서 언급 한 기능에 액세스 할 수 없었습니다. 그래서이 정확한 코드 라인은 jQuery(document).ready(function ($) {그것을 잘 고쳤습니다. 공유해 주셔서 감사합니다.
Devner

2
이것은 Drupal에서도 같은 문제입니다. 솔루션도 거기에서 작동합니다. 감사합니다
Yogesh Gupta 2014 년

35

내가 가장 좋아하는 충돌 방지 구조 :

jQuery(function($) {
  // ...
});

함수 포인터로 jQuery를 호출하는 것은 $ (document) .ready (...)

또는 우리가 coffeescript에서 말했듯이 :

jQuery ($) ->
  # code here

경우 $에 합격 할 이유 - 이미 JQuery와 인스턴스 jQuery와 그것에게주고 $다시 한 번 이름을?
zerkms

2
$는 다른 라이브러리 (비 충돌 모드)와 충돌하는 경우 jQuery 인스턴스가 아닐 수 있습니다.
Julian

4
그것은 바로 가기입니다 $(document).ready(), 아니$(document).on('load')
케빈 B

이것은 나를 위해 일했습니다! 내 테마의 모든 custom.js 기능이 설명 할 수없이 고장났습니다. 나는이와 함께 $ (문서) .ready (함수 () {교체가 : 마법처럼 일
아이라 허먼에게


1

다음과 같은 내용을 테마 functions.php 파일에 추가하여 기본 WordPress jQuery 스크립트를 Google 라이브러리로 대체하는 것을 고려할 수 있습니다.

function modify_jquery() {
    if (!is_admin()) {
        wp_deregister_script('jquery');
        wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', false, '1.10.2');
        wp_enqueue_script('jquery');
    }
}
add_action('init', 'modify_jquery');

여기에서 가져온 코드 : http://www.wpbeginner.com/wp-themes/replace-default-wordpress-jquery-script-with-google-library/


최상의 솔루션을 사용하는 경우 "외부"WP 단점의 JQuery와 플러그인 외부 : - 수 - 내 옆에 발견 아무것도 - 일부 워드 프레스 플러그인과 충돌
RunsnbunsN

-1

아마도 jquery 전에 다음과 같은 코드가있을 수 있습니다.

var $jq=jQuery.noConflict();
$jq('ul.menu').lavaLamp({
    fx: "backout", 
    speed: 700
});

그리고 그들은 갈등이었다

$를 (jQuery)로 변경할 수 있습니다.


1
나는처럼 사용 var $=jQuery.noConflict();광산 자바 웹 애플리케이션 설치했다,하지만 난 같은 오류가있어!
coding_idiot jul.
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.