检查“字数统计”时jQuery“keyup”崩溃页面

时间:2013-11-14 06:37:16

标签: javascript jquery html performance

我在DIV上运行了一个单词计数器,输入几个单词后,页面崩溃了。浏览器继续工作(滚动滚动)并且Chrome控制台中没有显示错误。不知道我哪里错了......

当我在“ keyup ”中传递“ wordCount(q); ”时,一切都开始了。我只是把它传给了那里,因为它会拆分“NaN”而不是一个数字来倒计时。

JS:

wordCount();

$('#group_3_1').click(function(){
    var spliced = 200;
    wordCount(spliced);
}) ;

$('#group_3_2').click(function(){
    var spliced = 600;
    wordCount(spliced);
}) ;

function wordCount(q) {
    var content_text = $('.message1').text(),
        char_count = content_text.length;

        if (char_count != 0) 
          var word_count = q - content_text.replace(/[^\w ]/g, "").split(/\s+/).length;
        $('.word_count').html(word_count + " words remaining...");

        $('.message1').keyup(function() {
          wordCount(q);
        });

        try
        {
            if (new Number( word_count ) < 0) {
                $(".word_count").attr("id","bad");
            }
            else {
                $(".word_count").attr("id","good");
            }
        } catch (error)
        {
            //
        }

  };

HTML:

<input type="checkbox" name="entry.3.group" value="1/6" class="size1" id="group_3_1">
<input type="checkbox" name="entry.3.group" value="1/4" class="size1" id="group_3_2">


<div id="entry.8.single" class="message1" style="height: 400px; overflow-y:scroll; overflow-x:hidden;" contenteditable="true"> </div>
<span class="word_count" id="good"></span>

先谢谢!

3 个答案:

答案 0 :(得分:2)

这导致无限循环if (new Number(word_count) < 0) {

你的代码完全混乱。只需研究并从更基本的概念入手,重新开始。如果你想在评论中向我描述你的项目,我很乐意向你展示一个好的,干净的,可读的方法。

<强>更新
在代码中拥有良好架构的一部分是将逻辑的不同部分分开。您的代码的任何部分都不应该知道或使用与其无直接关系的任何内容。请注意,在我的单词计数器中,它所做的任何事情都与它的单词计数器直接相关。一个词是否关心计数会发生什么?不。它只是计算并发送结果(通过回调函数,无论你告诉它的地方)。这不是唯一的方法,但我只是想让你了解如何更有意义地处理事情。

Live demo here (click).

/* what am I creating? A word counter.
 * How do I want to use it?
 * -Call a function, passing in an element and a callback function
 * -Bind the word counter to that element
 * -When the word count changes, pass the new count to the callback function
 */

window.onload = function() {
  var countDiv = document.getElementById('count');
  wordCounter.bind(countDiv, displayCount);
  //you can pass in whatever function you want. I made one called displayCount, for example
};

var wordCounter = {
  current : 0,
  bind : function(elem, callback) {
    this.ensureEditable(elem);
    this.handleIfChanged(elem, callback);

    var that = this;
    elem.addEventListener('keyup', function(e) {
      that.handleIfChanged(elem, callback);
    });
  },
  handleIfChanged : function(elem, callback) {
    var count = this.countWords(elem);
    if (count !== this.current) {
      this.current = count;
      callback(count);
    }
  },
  countWords : function(elem) {
    var text = elem.textContent;
    var words = text.match(/(\w+\b)/g);
    return (words) ? words.length : 0;
  },
  ensureEditable : function(elem) {
    if (
      elem.getAttribute('contenteditable') !== 'true' && 
      elem.nodeName !== 'TEXTAREA' &&
      elem.nodeName !== 'INPUT'
    ) {
      elem.setAttribute('contenteditable', true); 
    }
  }
};

var display = document.getElementById('display');
function displayCount(count) {
  //this function is called every time the word count changes
  //do whatever you want...the word counter doesn't care.
  display.textContent = 'Word count is: '+count;
}

答案 1 :(得分:1)

我可能会这样做

http://jsfiddle.net/6WW7Z/2/

var wordsLimit = 50;

$('#group_3_1').click(function () {
    wordsLimit = 200;
    wordCount();
});
$('#group_3_2').click(function () {
    wordsLimit = 600;
    wordCount();
});
$('.message1').keydown(function () {
    wordCount();
});

function wordCount() {
    var text = $('.message1').text(),
        textLength = text.length,
        wordsCount = 0,
        wordsRemaining = wordsLimit;

    if(textLength > 0) {
        wordsCount = text.replace(/[^\w ]/g, '').split(/\s+/).length;
        wordsRemaining = wordsRemaining - wordsCount;
    }
    $('.word_count')
        .html(wordsRemaining + " words remaining...")
        .attr('id', (parseInt(wordsRemaining) < 0 ? 'bad' : 'good'));

};  

wordCount();

它并不完美和完整,但它可能会告诉你如何做到这一点。如果选中/取消选中,则应在复选框上使用change event来更改wordsLimit。对于样式有效/无效单词剩余消息使用类而不是ID。

答案 2 :(得分:1)

我认为您应该使用radio代替checkboxes,因为您可以一次限制200600

试试这个,

wordCount();
$('input[name="entry.3.group"]').click(function () {
    wordCount();
    $('.word_count').html($(this).data('val') + " words remaining...");
});
$('.message1').keyup(function () {
    wordCount();    
});

function wordCount() {
    var q = $('input[name="entry.3.group"]:checked').data('val');
    var content_text = $('.message1').text(),
        char_count = content_text.length;
    if (char_count != 0) var word_count = q - content_text.replace(/[^\w ]/g, "").split(/\s+/).length;
    $('.word_count').html(word_count + " words remaining...");
    try {
        if (Number(word_count) < 0) {
            $(".word_count").attr("id", "bad");
        } else {
            $(".word_count").attr("id", "good");
        }
    } catch (error) {
        //
    }    
};

您也可以添加span bad id key up return false; {{1}}

请参阅Demo