我有一个文本框,每次用户按下一个键时,我都会计算该字段的新长度,以查看仍有多少字符可用。 根据这个数字,我:
但现在我遇到了问题;在每个 keydown 事件中,我这样做:
remaining = 100 - count;
if (remaining > 9)
{
//blue counter; send is activated
//"if counter.class == red then counter.class = blue..."
//"send.off('click'); send.on('click', sendmessage)..."
}
else if ((remaining <= 9) && (remaining >= 0))
{
//red counter; send is activated
}
else //remaining <0
{
//red counter; send is deactivated
}
每次用户按下某个键时,都会执行3个块中的一个...仅当变量更改为“zone”时才有执行块的方法(]∞, 9[
; {{1} }; [9,0]
)?
答案 0 :(得分:1)
毫无疑问,这可以更优雅地完成,但简单的答案就是记住以前的长度值:
var prevCount = 10;
function checkLength() {
var count = // your logic to get current count here
if (count > 9 && prevCount <=9) {
// count has changed to > 9
} else if (count <=9 && count >= 0 && (prevCount > 9 || prevCount < 0) {
// count has changed to <=9
} else if (count < 0 && prevCount >= 0) {
// count has changed to < 0
}
prevCount = count;
}
将prevCount
初始化为屏幕加载时有意义的任何值......
(P.S。计数如何小于零?)
更新:由于您已确认使用的是jQuery,因此您可以执行以下操作(假设“黑色”和“红色”是样式表中具有相应颜色和格式设置的类):
$(document).ready(function() {
var limit = 100,
$rem = $("#remaining").addClass("black"),
$send = $("input");
$("textarea").on("keydown keyup", function() {
var len = $(this).val().length,
remaining = limit - len;
$rem.text(remaining);
$send.prop("disabled", len === 0 || remaining < 0);
if (remaining <=9 && $rem.hasClass("black")
|| remaining > 9 && $rem.hasClass("red"))
$rem.toggleClass("black red");
}).keydown();
});
如果没有文字或文字太多,则禁用发送按钮;仅在必要时将班级从黑色更改为红色。 (您也可以将黑色设为默认值,只需打开和关闭“红色”类。)