WordPress jQuery Uncaught TypeError: Property '

2019-04-29 02:02发布

问题:

I'm converting my html files to a WordPress theme and I'm using the plugin ZClip for copy text to clipboard. The ZClip plugin works fine in my html demo, but when converting to WordPress I got this weird syntax error "Uncaught TypeError: Property '$' of object [object Object] is not a function" in line 288 in the zclip.js file which is

$(this.domElement).data('zclipId', 'zclip-' + this.movieId);

I think it is something with the variable $ not sure. I read something about the jQuery might get in conflict with each other in WP so I have changed my main.js file to

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

    ...
    $("button").zclip({
      path:'js/ZeroClipboard.swf',
      copy: function() { return $(this).attr("data-coupon"); }
    });
});

functions.php

<?php

function load_styles_and_scripts(){
    //load css
    wp_enqueue_style( 'main-styles', get_template_directory_uri().'/style.css' );

    // load scripts
    wp_enqueue_script( 'jquery', 'http://code.jquery.com/jquery-1.10.1.min.js' );
    wp_enqueue_script( 'zclip-script', get_template_directory_uri().'/js/zclip.js' );
    wp_enqueue_script( 'main-script', get_template_directory_uri().'/js/main.js' );

}

add_action('wp_enqueue_scripts', 'load_styles_and_scripts');

Finally figured this out after a full day, lol. Seems like the WP 3.5.2 load an older version of jQuery 1.8.3 and I using a new version and it it doesn't load because of this line

wp_enqueue_script( 'jquery', 'http://code.jquery.com/jquery-1.10.1.min.js' );

maybe 'jquery' is reserved for WP's local jquery installation I changed it to and my site starts to work, but according to a user here it is not recommended.

wp_enqueue_script( 'jq', 'http://code.jquery.com/jquery-1.10.1.min.js' );

回答1:

By default WordPress' jQuery runs in no conflict mode. Replace $ with jQuery in your code and it should work.

http://api.jquery.com/jQuery.noConflict/