开发者

jquery core not working in Wordpress

Problem Scripts on some pages that use jquery are not activating.

Scenario Finding that I couldn't get a script to work I put a very simple test script on a page in order to test that the jquery was functioning.

<script type="text/javascript">
$(document).ready(function (){
      $(".testJavascript").addClass("hover_red");
});
</script>
<p class="testJavascript">This paragraph is to test Javascript</p>

This should add a red border but it will not function.

Troubleshooting I've Tried I checked for the presence of the jquery core and it appears in the header of the page. Its enqueued and appears to be working correctly on some other pages, so I have no reason to suspect that its been corrupted.

I tried the following tests:

  • Put the above script in the header template, just before the closing header tag
  • Put the script in the body of the 开发者_JAVA百科page right above the test paragraph to which it relates
  • Enqueued the script in case there was some sort of conflict that I wasn't anticipating. This caused the page to stop loading - can't see why this would cause a problem.. EDIT: After further testing I suspect this was caused by the $ vs jQuery nomenclature. Having changed it the enqueueing of this script no longer stops the page loading. however, the script still doesn't work.
  • Finally since I'm a novice and I always suspect that I'm the cause of the problem I put the script and html snippet onto a page on my local MAMP server. It worked as expected. I think this exonerates my coding but maybe not.

I'm bemused as to what the cause of the problem might be.

I'd appreciate any suggestions as to where to look for the possible source of the problem.

Thanks.


One possible problem could be that your testJavascript class has a border in css and appears before hover_red class. If that's the case, switch them, so hover_red will come after testJavascript in your css file (or within style tags)


If you're having jQuery conflict try it using noConflict()

<script type="text/javascript">
    jQuery.noConflict();
    jQuery(document).ready(function ($) {
          $(".testJavascript").addClass("hover_red");
    });
</script>


Answering My Own Question

The final solution to this problem was to enqueue the style sheet related to the test script. I had referenced the css file by using a standard link in the header, added in the header template above the ending header tag. It appears that this wasn't working because when I enqueued the style file the script worked.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜