我正在创建一个包含四个textarea表单的网站。每个表单都有一个字数限制。
我尝试使用我在尝试修复此问题时找到的现有示例,但似乎没有任何效果。
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
var maxwords = 250;
//
function check_length(obj, cnt, rem)
{
var ary = obj.value.split(" "); // doubled spaces will throw this off
var len = ary.length;
cnt.innerHTML = len;
rem.innerHTML = maxwords - len;
if (len > maxwords) {
alert("Message in '" + obj.name + "' limited to " + maxwords + " words.");
ary = ary.slice(0,maxwords-1);
obj.value = ary.join(" "); // truncate additional words
cnt.innerHTML = maxwords;
rem.innerHTML = 0;
return false;
}
return true;
}
</script>
HTML
<textarea name="Message 1" onkeypress="
return check_length(this,
document.getElementById('count1'),
document.getElementById('remaining1'));"></textarea>
Word count: <span id="count1">0</span>
Words remaining: <span id="remaining1">250</span>
<textarea name="Message 2" onkeypress="
return check_length(this,
document.getElementById('count2'),
document.getElementById('remaining2'));"></textarea>
Word count: <span id="count2">0</span>
Words remaining: <span id="remaining2">500</span>
有没有人知道这个问题的解决方案?
提前致谢, 汤姆
答案 0 :(得分:1)
在函数中添加一个额外的参数,并从每个函数调用中发送maxWords:
function check_length(obj, cnt, rem, maxwords)
{
//... rest of the function would stay the same
当你打电话时,请加上最多的单词
<textarea name="Message 2" onkeypress="
return check_length(this,
document.getElementById('count2'),
document.getElementById('remaining2'), 250);"></textarea>
Word count: <span id="count2">0</span>
Words remaining: <span id="remaining2">500</span>
要删除剩下的字词,
function check_length(obj, cnt, maxwords)
{
var ary = obj.value.split(" "); // doubled spaces will throw this off
var len = ary.length;
cnt.innerHTML = len;
if (len > maxwords) {
alert("Message in '" + obj.name + "' limited to " + maxwords + " words.");
ary = ary.slice(0,maxwords-1);
obj.value = ary.join(" "); // truncate additional words
cnt.innerHTML = maxwords;
return false;
}
return true;
}
并在您的HTML中
<textarea name="Message 1" onkeypress="
return check_length(this,
document.getElementById('count1'),250);"></textarea>
Word count: <span id="count1">0</span>
答案 1 :(得分:0)
你的功能问题在于你总是在检查maxwords
变量插入的单词数量(设置为250个单词作为第一个textarea限制)
所以更好的尝试是将额外的参数传递给具有原始限制的函数(每个文本区域不同)
答案 2 :(得分:0)
为这些textareas插入class
属性(如class='area250'
,class='area500'
等),然后在函数中包含if语句
function check_length(obj, cnt, rem)
{
if(window.event.srcElement.getAttribute('class')=='area250')
maxwords=250;
else if(window.event.srcElement.getAttribute('class')=='area500')
maxwords=500;
else .......................................
}