doujing3896 2014-12-26 13:40
浏览 159
已采纳

如何将jquery添加到wordpress插件

This could be a very easy question to wordpress expert. I am a newbie in wordpress and I am having problem using jquery on it. The jquery library is already included because you can see it firebug

I dont know what I am missing here.

This is my code..

add_action( 'wp_enqueue_scripts', array( $this, 'jsscript' ) );


function jsscript() {   
    ?>
    <script type="text/javascript">
        $(document).ready(function(){
            alert('here!');
        });
    </script>
    <?php
    }

The jsscript is already on the firebug but it doesn't work. I am getting this error message in firebug.

ReferenceError: $ is not defined
$(document).ready(function(){

I read somewhere that it is not a good idea to include another jquery library and it make sense not to load it again.

I hope somebody can help me.

Thanks in advance.

  • 写回答

4条回答

  • dongqin6926 2014-12-26 13:48
    关注

    Instead of just randomly outputting your script you should add it in an external file in your plugin directory, and then include that file with jQuery as a dependency

    wp_enqueue_script(
          'jsscript', 
          plugin_dir_path( __FILE__ ) . '/jsscript.js', 
          array( 'jquery' )
    );
    

    The issue you're having now, is that there's no guarantee that the script is outputted after jQuery, in fact there's now guarantee that the script tag you're outputting between the PHP tags is inserted where it's supposed to go at all.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条