【问题标题】:Using JQuery with Wordpress the Right Way?以正确的方式使用 JQuery 和 Wordpress?
【发布时间】:2011-11-17 07:56:08
【问题描述】:

我一直在为 Wordpress 使用我的自定义(不是插件)jquery 幻灯片。我整天都在寻找如何在 Wordpress 中集成 javascript,但似乎遇到了许多不同的方式。所以我的主要问题是哪种方式是编写脚本的正确、最快的方式。

从我阅读的内容看来,我应该使用 Wordpress enqueue,以便仅在需要它的页面上调用脚本,在我的情况下是 index.php。但我不确定正确的方法。另外,我应该在我的functions.php中添加一些东西吗?

这是脚本:

<script src="Js/js/jquery-1.6.1.min.js" type="text/javascript"></script>
<script src="Js/js/jquery.zaccordion.js" type="text/javascript"></script>
<script type="text/javascript"> 
  $(document).ready(function() {
    $("#example4 ul").zAccordion({
        slideWidth: 600,
        width: 900,
        height: 250,
        timeout: 5000,
        slideClass: "frame"
    });
  });
</script>

这就是我现在在 header.php 中的内容:

<?php wp_enqueue_script('jquery'); ?> 
<?php wp_head();?>
<script type="text/javascript"
        src="<?php bloginfo("template_url"); ?>/js/jquery-1.6.1.min.js"></script>
<script type="text/javascript"
        src="<?php bloginfo("template_url"); ?>/js/jquery.zaccordion.js"></script>

<script type="text/javascript">
  jQuery.noConflict();
  jQuery(document).ready(function() {
    jQuery("#slider ul").zAccordion({
        slideWidth: 600,
        width: 800,
        height: 250,
        timeout: 5000,
        slideClass: "frame"
    });
  });
</script>

【问题讨论】:

    标签: javascript jquery wordpress


    【解决方案1】:

    我的建议(和解决方案):

    WordPress 插件开发 - 初学者指南 Packtlib 按下

    这是一本非常好的书,非常清晰、简单,并且有大量的优秀示例可以用于 jQuery。

    此外,您还有每个人在编写 Wordpress 插件时都应该做的真实事情;)

    【讨论】:

      【解决方案2】:

      如果您不想创建插件,那么第二好的解决方案是安装 Headspace2 插件,该插件允许您从 Wordpress 管理员编辑页面/发布屏幕将任何 JS 或 CSS 文件添加到任何页面。

      另外,我会将你的内联 JS 转换为外部 JS 文件 (mycustom.js),然后像你处理其他 JS 文件一样包含它,但这是我个人的偏好。

      【讨论】:

        【解决方案3】:

        我可以建议以下几点:

        1. 不要包含您的 .js,因为您已经将它们排入队列
        2. 使用 wp_register_script 注册您的 jquery.zaccordion.js,然后像使用 jquery 一样将其加入队列
        3. 您不需要包含 jQuery.noConflict();,因为 WordPress 的 jQuery 已经声明了它。只有当您包含自己的 jQuery 时,您才需要

        【讨论】:

          【解决方案4】:

          您可以在您的主题文件中包含 jQuery,并将其命名为 functions.php 文件。在我的情况下,脚本位于 js 文件夹(your_theme/js/)中。

          在 WordPress 中加载脚本的正确方法是使用函数wp_enqueue_script

          在你的主题类型的functions.php中:

          /**
           * Load jQuery script
           */
          if (!is_admin()) {
              function register_my_jquery() {
                  wp_deregister_script( 'jquery' );
                  wp_register_script( 'jquery', get_bloginfo('template_directory') . "/js/jquery.min.js" );
                  wp_enqueue_script( 'jquery' );
              }
              add_action('init', 'register_my_jquery');
          }
          

          【讨论】:

            猜你喜欢
            • 2017-01-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-10-15
            • 1970-01-01
            • 1970-01-01
            • 2019-06-07
            • 2018-09-10
            相关资源
            最近更新 更多