当前位置: 动力学知识库 > 问答 > 编程问答 >

Try to get jQuery working on a Wordpress site (Bones theme)

问题描述:

I try to get jQuery working on a Wordpress site. It's all working on my no-wordpress version but i have hard time to adapt it in worpress. I tried to run a simple script:

I have this in my theme functions.php:

wp_enqueue_script('jquery');

function add_my_script() {

wp_enqueue_script(

'test', get_template_directory_uri() . '/js/test.js', array('jquery')

);

}

add_action('init', 'add_my_script');

And this is the test script i want to run, test.js:

$(document).ready(function() {

alert('hi');

});

I don't know what i am doing wrong :S

网友答案:
  1. Make sure the code in your functions.php is actually enqueuing the scripts you need (view source of the page).
  2. As far as I remember, WordPress enqueues jquery by default.
  3. If you want to use the jquery version that wordpress enqueued, then you have to use the jQuery keyword instead of $ eg:

    jQuery(document).ready(function() { alert('hi'); jQuery('div').hide(); });
  4. if you want to use another version of jQuery (i prefer this way) then you have to DEREGISTER the enqueued-by-wordpress version of jquery. Then you have to register the version of jquery and then enqueue it. This applies for all scripts included by WordPress. Remember: deregister, register, enqueue.

  5. The enqueue functions should be inside your add_my_script function

  6. add_my_script function should hook to the wp_enqueue_scripts action: add_action('wp_enqueue_scripts','add_my_script');

  7. Codex is your friend.

分享给朋友:
您可能感兴趣的文章:
随机阅读: