如何正确包含jQuery?

时间:2018-08-23 作者:Ooker

我有一个需要jQuery的脚本,我不知道如何将它正确地添加到帖子中。我读过How to include jQuery and JavaScript files correctly?Using JavaScript and JQuery in Page 但它们太先进了,我无法理解。Scripts\'n Styles插件有Include Scripts部分,我怀疑这是另一种使用方式wp_enqueue_script, 但我不知道该选哪一个:

到目前为止,我只添加了<head><body> 没有jQuery的元素,虽然它最终起作用了,但在一开始就不起作用了,我不得不多次尝试。那么,有没有一种合适且简单的方法来做到这一点?


仅供参考:How to add JavaScript code on WordPress correctly?

代码如下。

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script>
    var words = [];

    words.push(\'vocabulary\');
    words.push(\'lexicon\');
    words.push(\'lexicons\');

  </script>

</head>

<body>

  <p id="demo">A vocabulary is a list of words that an individual knows or uses regularly. vocabulary is different from lexicon because vocabulary is about what an individual or group of people know, whereas lexicon is about the language itself. In this paragraph, lexicons is a new word that\'s added, so don\'t forget to push \'lexicons\' in your array.
  </p>

  <script>
    function toggle(element) {
      if (element.innerHTML.split(\'_\').join(\'\').trim().length === 0) {
        element.innerHTML = element.getAttribute("word");
      } else {
        element.innerHTML = "_______";
      }
    }

    $.each(words, function(index, value) {
      var replacestr = new RegExp(\'\\\\b\'+value+\'\\\\b\', "g");
      $("p#demo:contains(\'" + value + "\')").html(function(_, html) {
        return html.replace(replacestr, \' <span class = "smallcaps" word="\' + value + \'" onclick="toggle(this)">_______</span>\')
      });
    });
  </script>
</body>

</html>

2 个回复
SO网友:maverick

假设您已将所有内容(脚本文件和样式文件)正确地排入wordpress主题文件夹中

以下是(假设)您的主题文件

wp-content/themes/your-theme-dir/
                   assets/
                      css/   ( this is directory/folder )
                        styles.css  ( this is file )
                      js/
                        scripts.js
                   index.php
                   functions.php
假设上面显示的代码在索引中。php

现在假设您已经包含了脚本。函数中的js文件。php文件

脚本中的内容。js文件应如下所示:

(function($){
    var words = [];

    words.push(\'vocabulary\');
    words.push(\'lexicon\');
    words.push(\'lexicons\');
    function toggle(element) {
      if (element.innerHTML.split(\'_\').join(\'\').trim().length === 0) {
        element.innerHTML = element.getAttribute("word");
      } else {
        element.innerHTML = "_______";
      }
    }

    $.each(words, function(index, value) {
      var replacestr = new RegExp(\'\\\\b\'+value+\'\\\\b\', "g");
      $("p#demo:contains(\'" + value + "\')").html(function(_, html) {
        return html.replace(replacestr, \' <span class = "smallcaps" word="\' + value + \'" onclick="toggle(this)">_______</span>\')
      });
    });
})(jQuery);
记住,当enqueunig脚本时,您的文件应该依赖于jquery,比如

wp_enqueue_script( \'file-id\', \'path-to-file\', array( \'jquery\' ), \'version-number\', \'true\' );
要获取文件路径,有两个选项

如果主题是父主题,请使用:get_template_directory_uri()e、 g.get\\u template\\u directory\\u uri()。\'/资产/js/脚本。js\'

如果主题是子主题,请使用:get_stylesheet_directory_uri()e、 g.get\\u stylesheet\\u directory\\u uri()。\'/资产/js/脚本。js\'

SO网友:Tedinoz

我用严格的html格式测试了这段代码,jQuery可以正常工作。

然后我在WordPress中将这个问题的答案编码为1)一个插件,2)从函数加载。php。在每种情况下,jQuery都会失败。

在我未经培训的眼中,这个问题似乎与Javascript有关。特别是因为方法“toggle(element)”在执行“$.each”时是一个全局对象。在某种程度上,我认为两者需要相互联系,但尽管我花了一天的大部分时间在这方面,这超出了我的能力。当然,这是有风险的PEBCAK。

The content as displayed (证明$已成功运行)
enter image description here

The content HTMLenter image description here

Chrome Console before clicking on the text:
enter image description here

Chrome Console after clicking on a blank work in the text

enter image description here


插件包括:1-插件文件(vocab.php)
2-插件Javascript文件(vocab.js)
3-插件模板内容文件(vocab Template.php)
4-页面模板(Page vocab.php)(模板名称=vocab Test)
加上一个标准WordPress页面,模板=“vocab Test”

The Plugin file (vocab.php)

<?php
/*
Plugin Name: a_Stackoverflow_Vocab test
*/
// 01 - Define the filesystem paths for the plugin

if ( ! defined( \'WP_CONTENT_URL\' ) )
      define( \'WP_CONTENT_URL\', get_option( \'siteurl\' ) . \'/wp-content\' );
if ( ! defined( \'WP_CONTENT_DIR\' ) )
      define( \'WP_CONTENT_DIR\', ABSPATH . \'wp-content\' );
if ( ! defined( \'WP_PLUGIN_URL\' ) )
      define( \'WP_PLUGIN_URL\', WP_CONTENT_URL. \'/plugins\' );
if ( ! defined( \'WP_PLUGIN_DIR\' ) )
      define( \'WP_PLUGIN_DIR\', WP_CONTENT_DIR . \'/plugins\' );
define( \'VOCAB_DIR\', plugin_dir_path( __FILE__  ) );
define( \'VOCAB_URL\', plugin_dir_url( __FILE__  ) );

// 02 - Enqueue scripts and styles for the plugin. 

function vocab_scripts() {
    if (!is_admin()) {
            if (is_page(array(\'vocab\'))) { 
                wp_enqueue_script( \'jquery\' );
                wp_register_script(\'vocabjs\',  VOCAB_URL . \'vocab.js\', array( \'jquery\'),NULL);  
                wp_enqueue_script(\'vocabjs\'); 
            }
    }
}
add_action( \'wp_enqueue_scripts\', \'vocab_scripts\' );

// Calls to key files: template layout

require("vocab-template.php"); 

?>
The Javascript file (vocab.js)

jQuery(document).ready(function ($) {
    var words = [];
    words.push(\'vocabulary\');
    words.push(\'lexicon\');
    words.push(\'lexicons\');

function toggle(element) {
  if (element.innerHTML.split(\'_\').join(\'\').trim().length === 0) {
    element.innerHTML = element.getAttribute("word");
  } else {
    element.innerHTML = "_______";
  }
}

$.each(words, function(index, value) {
  var replacestr = new RegExp(\'\\\\b\'+value+\'\\\\b\', "g");
  $("p#demo:contains(\'" + value + "\')").html(function(_, html) {
    return html.replace(replacestr, \' <span class = "smallcaps" word="\' + value + \'" onclick="toggle(this)">_______</span>\')
  });
});
});
The Plugin Template content file (vocab template.php)

<?php
/*
*       function to deliver template
*/
function insert_vocab_template(){
?>
<div id="page">
<!-- start div page -->
    <h1>Vocabulary Test</h1>
        <div id="cover_content">
            <h2>Test content</h2>
                <p id="demo">A vocabulary is a list of words that an individual knows or uses regularly. vocabulary is different from lexicon because vocabulary is about what an individual or group of people know, whereas lexicon is about the language itself. In this paragraph, lexicons is a new word that\'s added, so don\'t forget to push \'lexicons\' in your array.</p>
        </div>
        <!-- end cover_content -->
    </div> 
    <!-- end #page -->
<?php
}
?>
The Page Template (第vocab.php页)

<?php /* Template Name: Vocab Test */ ?>
<?php
get_header(); ?>
    <div id="primary" class="content-area">
        <main id="main" class="site-main" role="main">
        <!-- page -->
            <?php
            $myoutput = insert_vocab_template();
            echo $myoutput;
            ?>
        </main><!-- .site-main -->
    </div><!-- .primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
<小时>Alternative via Functions.php (在儿童主题中)

1-将函数排入函数队列。php(主题/子主题/js)-vocab2。js(与插件版本相同)
3-页面模板(Page-vocab2.php)(模板名称=vocab2 Test)
加上一个标准WordPress页面,模板=“Vocab Test2”
注意:在这个版本中,文本段落(id=“demo”)作为内容包含在WordPress页面中。

Extract from Functions.php

// enqueue jquery and script
function vocab2_scripts() {
    if (!is_admin()) {
            if (is_page(array(\'vocab2\'))) { 
                wp_enqueue_script(\'jquery\');
                wp_enqueue_script(\'vocab2js\', get_stylesheet_directory_uri(). \'/js/vocab2.js\', array( \'jquery\' ));  
            }
    }
}
add_action( \'wp_enqueue_scripts\', \'vocab2_scripts\' );
The Javascript file (主题/儿童主题/js)-vocab2。js公司

jQuery(document).ready(function ($) {
    var words = [];

    words.push(\'vocabulary\');
    words.push(\'lexicon\');
    words.push(\'lexicons\');

    function toggle(element) {
      if (element.innerHTML.split(\'_\').join(\'\').trim().length === 0) {
        element.innerHTML = element.getAttribute("word");
      } else {
        element.innerHTML = "_______";
      }
    }

    $.each(words, function(index, value) {
      var replacestr = new RegExp(\'\\\\b\'+value+\'\\\\b\', "g");
      $("p#demo:contains(\'" + value + "\')").html(function(_, html) {
        return html.replace(replacestr, \' <span class = "smallcaps" word="\' + value + \'" onclick="toggle(this)">_______</span>\')
      });
    });
});
The Page Template (page-vocab2.php)(模板名称=vocab2测试)

<?php /* Template Name: Vocab Test2 */ ?>
<?php
get_header(); ?>
<div id="primary" class="content-area">
    <main id="main" class="site-main" role="main">
    <!-- page -->
        <?php
        while ( have_posts() ) : the_post();
        ?>
            <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
                <header class="entry-header">
                    <?php the_title( \'<h1 class="entry-title">\', \'</h1>\' ); ?>
                </header><!-- .entry-header -->

                <div class="entry-content">
                    <?php the_content();?>
                </div><!-- .entry-content -->
            </article><!-- #post-## -->
        <?php
            // End of the loop.
        endwhile;
        ?>
    </main><!-- .site-main -->
</div><!-- .content-area -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>

UPDATE:

现在,我可以通过使用“$.each”语句从中调用“toggle”使代码正常工作,但控制台仍在给出错误-现在更改为:“UncaughtTypeError:无法读取未定义的属性‘innerHTML’”
enter image description here

Javascript文件现在如下所示:

function toggle(element) {
      if (element.innerHTML.split(\'_\').join(\'\').trim().length === 0) {
        element.innerHTML = element.getAttribute("word");
      } else {
        element.innerHTML = "_______";
      }
}

jQuery(document).ready(function ($) {
    var words = [];

    words.push(\'vocabulary\');
    words.push(\'lexicon\');
    words.push(\'lexicons\');
    $.each(words, function(index, value) {
      var replacestr = new RegExp(\'\\\\b\'+value+\'\\\\b\', "g");
      $("p#demo:contains(\'" + value + "\')").html(function(_, html) {
        return html.replace(replacestr, \' <span class = "smallcaps" word="\' + value + \'" onclick="toggle(this)">_______</span>\')
      });
    });
        toggle();
});

结束