jQuery Script fails to load in Wordpress ($ is not

2019-08-07 23:49发布

问题:

I've been working on a version of Ian Lunn's interactive map embeded into wordpress.

The script works perfectly on a standalone page, but when loaded into wordpress, the script does nothing. I've tried various solutions - loading the jQuery in different ways (in functions.php, inline, in the header and footer), downgrading to an earlier version of jQuery, namespacing the functions, you name it. Nothing happens, firebug shows no errors, nothing.

I'm at a complete loss at this stage, any help offered would be greatly appreciated.

Working demo here: http://www.ianlunn.co.uk/demos/bbc-news-jquery-map/ Github source: https://github.com/IanLunn/BBC-News-jQuery-Map

//Update after answers

It transpires that the the dollar sign is reserved in WordPress for the Prototype library, which is why it errors out with '$ is not a function' - the accepted answer below points this out but only in the comments hence the update for clarity. For example:-

$().ready(function() {
   $("#select_me").show();
});

jQuery().ready(function() {
   jQuery("#select_me").show();
});

回答1:

I see two errors in the Firebug console when I go to your page.

First is:

XML can't be the whole program.
?>    map.js?ver3.2.1 (line 55)

Second is:

document.getElementById("recaptcha-submit-btn-area") is null
/about/...ve-map/ (line 595)

Then I see:

carouFredSel: No element selected.
jquery...r=1.4.2 (line 14)

You don't see this output?

EDIT: Your map.js has code wrapped in PHP tags, that's the problem. It's PHP code being delivered to the client in a Javascript file.



回答2:

I know this has been answered already, but this is how I learned to do this and even though it's essentially the same answer, it might help others to be able to just copy/paste the solution.

Basically wrap all jQuery inside this function:

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

    /* Put your jQuery functions here,
       no need to change the $ to jQuery. */


});


回答3:

Take a look at the script file you're loading:

http://mjw.view-wireframes.com/jquery-map/map.js

Wordpress is spitting out a PHP file, rather than the .js file. I.e. it seems to be a problem in the way WP is serving or you are including the Javascript file.