JSFiddle:http: //jsfiddle.net/qPvch/62/
我在一个页面中有两个文本框。我希望第一个字数上限为 5,第二个字数上限为 6。
HTML:
<textarea name="what" id="five" rows="1" placeholder="limit 5 words"></textarea>
<div class="word_count_5">
Word count: <span>0</span>
</div>
<textarea name="what" id="six" rows="1" placeholder="limit 6 words"></textarea>
<div class="word_count_6">
Word count: <span>0</span>
</div>
查询:
var maxWords1 = 5;
jQuery('textarea#five').keypress(function() {
var $this, wordcount;
$this = $(this);
wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;
if (wordcount > maxWords1) {
jQuery(".word_count_5 span").text("" + maxWords1);
return false;
} else {
return jQuery(".word_count_5 span").text(wordcount);
}
});
var maxWords2 = 6; //REPEATING MYSELF
jQuery('textarea#six').keypress(function() {
var $this, wordcount;
$this = $(this);
wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;
if (wordcount > maxWords2) {
jQuery(".word_count_6 span").text("" + maxWords2);
return false;
} else {
return jQuery(".word_count_6 span").text(wordcount);
}
});