【发布时间】:2014-03-04 08:06:33
【问题描述】:
我有一个简单的代码来计算一个句子中的单词数。这个单词计数器有 3 个部分,一个 CSS、JS 和 HTML 文件。我知道它可以在 WordPress 中运行这个脚本,但我不知道如何实现这一点。以下是代码:
JS:
$(function() {
$("#sys-tbox").each(function() {
var input = '#' + this.id;
counter(input);
$(this).keyup(function() {
counter(input);
});
});
});
function counter(field) {
var number = 0;
var text = $(field).val();
var word = $(field).val().split(/[ \n\r]/);
words = word.filter(function(word) {
return word.length > 0
}).length;
$('.words').text(words);
$('.character').text(text.length);
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Sysadmin Word Counter</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="js/jscript.js"></script>
<link rel="stylesheet" href="css/css-style.css" />
</head>
<body>
<div id="sys-mbox">
<textarea id="sys-tbox"></textarea>
</div>
<div class="sys-results">
Total number of words: <span class="words"> </span>
Total number of chars: <span class="character"> </span>
</div>
</body>
</html>
这是Fiddle
我在 WordPress 文档中读到,这可以使用 wp_enqueue_script() 来实现,但我不确定从哪里开始,因为它的出现方法可能会根据文件结构使用的 WordPress 主题而有所不同不一样。
请任何人指出正确的方向或向我提供类似已回答问题的链接。
谢谢
将此代码添加到 Function.php:
function wordcount_scripts()
{
// Register the script like this for a plugin:
wp_register_script( 'wordcountjs', plugins_url( '/js/wordcountjs.js', __FILE__ ) );
// or
// Register the script like this for a theme:
wp_register_script( 'wordcountjs', get_template_directory_uri() . '/js/wordcountjs.js' );
// For either a plugin or a theme, you can then enqueue the script:
wp_enqueue_script( 'wordcountjs' );
}
add_action( 'wp_enqueue_scripts', 'wordcount_scripts', 5 );
【问题讨论】:
标签: javascript html css wordpress