我是否在这个字符限制计数器中实现了正确的if语句?

Did I implement the right if statement in this character limit counter?

本文关键字:实现 语句 if 计数器 是否 字符      更新时间:2023-09-26

使用这段代码,我试图实现一个字符限制计数器,我希望计数器说" Over!

当它达到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>

JSFiddle演示

   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!";
    }

编辑

请使用下面的代码:

 <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时,"Over!!"将自动出现。

点击此处:http://jsfiddle.net/bh3r77pe/