WordPress解决方案在jquery 1.11.0中不工作

Word Counter plugin in textarea WordPress solution not working in jquery 1.11.0

本文关键字:工作 解决方案 jquery WordPress      更新时间:2023-09-26

我已经用这个线程的代码设置了我的表单:计数和限制文本区域中的单词

然而,小提琴代码是用jQuery 1.8.3编写的,它工作得很好,然而,我的wordpress网站使用jQuery 1.11.0 -我需要对代码做什么样的修改才能使用这个版本的jQuery ?下面的代码…

谢谢你的帮助。

<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(function(){
$(document).ready(function() {
    $("#word_count").on('keydown', function(e) {
        var words = $.trim(this.value).length ? this.value.match(/'S+/g).length : 0;
        if (words <= 200) {
            $('#display_count').text(words);
            $('#word_left').text(200-words)
        }else{
            if (e.which !== 8) e.preventDefault();
        }
    });
 }); 
});//]]>  
</script>
  <textarea name="txtScript" id="word_count" cols="30" rows="10"></textarea>
Total word Count : <span id="display_count">0</span> words. Words left : <span id="word_left">200</span>

好吧,这不是jQuery版本有影响,如果我改变你在这引用的fiddle计数和限制单词在文本区域的答案在这里找到http://jsfiddle.net/7DT5z/9/使用jQuery 1.11.0,如这里所见http://jsfiddle.net/robschmuecker/7DT5z/21/它仍然工作。

我相信这是jQuery默认包含在wordpress中的方式,你在正常模式下引用jQuery,但它默认包含在wordpress的noConflict模式中,这意味着$(别名如果jQuery)不可用,你需要使用jQuery

所以你的代码需要读:

jQuery(function(){
jQuery(document).ready(function() {
    jQuery("#word_count").on('keydown', function(e) {
        var words = jQuery.trim(this.value).length ? this.value.match(/'S+/g).length : 0;
        if (words <= 200) {
            jQuery('#display_count').text(words);
            jQuery('#word_left').text(200-words)
        }else{
            if (e.which !== 8) e.preventDefault();
        }
    });
 }); 
});

另一种更简单的修改引用缩写别名$的代码的方法是这样的。-正如这里漂亮的解释和演示http://digwp.com/2011/09/using-instead-of-jquery-in-wordpress/

jQuery(document).ready(function( $ ) {
$("#word_count").on('keydown', function(e) {
        var words = $.trim(this.value).length ? this.value.match(/'S+/g).length : 0;
        if (words <= 200) {
            $('#display_count').text(words);
            $('#word_left').text(200-words)
        }else{
            if (e.which !== 8) e.preventDefault();
        }
    });
    });