使用这段代码,我试图实现一个字符限制计数器,我希望计数器说“结束!”当它达到 0 时以红色字母显示,但当用户删除字符时返回计数。
到目前为止,这是我的代码,但我觉得好像我使用了错误的 if
语句,因为它似乎无法正常工作。
<textarea id="ta" rows="1" style="width:340px;"
onKeyDown="textCounter(this.form.ta,this.form.countDisplay);"
onKeyUp="textCounter(this.form.ta,this.form.countDisplay);"></textarea>
<input readonly type="text" name="countDisplay" size="3" maxlength="3" value="15">
<button type="button" onclick="myFunction()">Preview</button>
<p id="go"></p>
<script>
function myFunction() {
var x = document.getElementById("ta").value;
document.getElementById("go").innerHTML = x;
}
if (function myFunction() < 0) {
document.getElementById("go").innerHTML = "Over!"; // tried implementing the red and the alert
}
</script>
最佳答案
function myFunction() {
var x = document.getElementById("ta").value;
document.getElementById("go").innerHTML = x;
return x;
}
你没有在 myFunction() 中返回任何东西
在您的 if 语句中,删除“function”关键字:
if (myFunction() < 0) {
document.getElementById("go").innerHTML="Over!";
}
编辑
您好,请使用此代码:
HTML
<form>
<textarea id="ta" rows="1" style="width:340px;"onKeyDown="textCounter(this.form.ta,this.form.countDisplay);" onKeyUp="textCounter(this.form.ta,this.form.countDisplay);"></textarea>
<input readonly type="text" name="countDisplay" size="3" maxlength="3" value="15">
<p id="go"></p>
</form>
JavaScript
var maxAmount = 15;
function textCounter(textField, showCountField) {
if (textField.value.length > maxAmount) {
textField.value = textField.value.substring(0, maxAmount);
} else {
showCountField.value = maxAmount - textField.value.length;
}
myFunction(showCountField.value);
}
function myFunction(value) {
if(value<=0)
{
document.getElementById("go").innerHTML = "<span style='color:red'>Over!!</span>";
}
else
{
document.getElementById("go").innerHTML = value;
}
}
我修改了你的代码,删除了预览按钮和“结束!!”计数到0时自动出现。
在这里 fiddle :http://jsfiddle.net/bh3r77pe/
关于javascript - 我是否在此字符限制计数器中实现了正确的 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31799332/