0

我有一个在 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>

先谢谢了!

4

3 回答 3

2

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

您的代码完全是一团糟。只需学习并从更基本的概念开始,然后重新开始。如果你想在评论中向我描述你的项目,我很乐意向你展示一个好的、干净的、可读的方法。

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

现场演示(点击)。

/* 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;
}
于 2013-11-14T06:45:13.370 回答
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();

它并不完美和完整,但它可能会向您展示如何做到这一点。如果选中/未选中,您应该在复选框上使用更改事件来更改 wordsLimit。对于剩余消息的有效/无效单词样式,请使用类而不是 id。

于 2013-11-14T06:44:09.673 回答
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;

演示

于 2013-11-14T06:56:58.510 回答