使用Javascript:
$(document).ready(function()
{
$('#field').keyup(function()
{
var count = '??';
$('#count').html(count);
});
});
HTML:
示例(单词始终用逗号分隔):
example 1: word,word word
count: (5 - 2) = 3
example 2: word
count: (5 - 1) = 4
example 3: word,word,count: (5 - 2) = 3
example 4: word,word
count: (5 - 3) = 2
因此,我需要计算用逗号分隔的单词数量,但是例如如示例3所示,只有当逗号后面还有单词时,才应将它们计为3个单词.
并且不应允许用户输入超过5个单词.
最佳答案
就像是:
$("#input").keyup(function(){
var value = $(this).val().replace(" ","");
var words = value.split(",");
if(words.length > 5){
alert("Hey! That's more than 5 words!");
$(this).val("");
}
});
jsFiddle示例:http://jsfiddle.net/BzN5W/
编辑:
更好的例子:http://jsfiddle.net/BzN5W/2/
$("#input").keypress(function(e){
var value = $(this).val().replace(" ",");
if(words.length > 5){
//alert("Hey! That's more than 5 words!");
e.preventDefault();
}
});