这是计算字符串的最佳方法吗

时间:2021-01-13 20:20:58

标签: javascript html

我正在更多地使用 html 来添加到我的网站,在这个问题 Dissappear content with html 之后,我现在有一个电话号码框,我的 javascript 代码告诉我输入框中有多少个字符,但是还包括空格。无论如何,我的javascript是否可以计算出不包括空格的字符数?

<!DOCTYPE html>
<html>
<body>

  <p>Click the button to return the number of characters in the string "Hello World!".</p>
  <input id="id"></input>
  <button onclick="myFunction()">Try it</button>

  <p id="demo"></p>

<script>
function myFunction() {
  var a = document.getElementById("id").value
  var str = a
  var n = str.length;
 
  if(n==10) {
    document.getElementById("demo").innerHTML = "Equal to 10"
  }
  else {
    document.getElementById("demo").innerHTML = "Not equal to 10"
  }
}
</script>

</body>
</html>

3 个答案:

答案 0 :(得分:1)

您没有在代码中定义 rowHeight。删除“幻数”"Hello World"(它应该是10,除非空格和标点符号不算在内)并将其替换为所需的字长。

此外,使用三重等号 (11) 进行值和类型比较。

===
const
  targetWord   = "Hello World",
  targetLength = targetWord.length;

function myFunction() {
  const str = document.getElementById("id").value;
  
  document.getElementById("demo").textContent = str.length === targetLength
    ? `Equal to ${targetLength}`
    : `Not equal to ${targetLength}`;
}

答案 1 :(得分:1)

您可以并且应该对您的代码(HTML 和 JavaScript)做很多事情。其中一些会使其更加优化,而另一些则是因为您使用的是过时的技术,而这些技术应该被现代的标准方法所取代。

查看内嵌评论了解详情:

<!DOCTYPE html>
<html>
<!-- An HTML document must have a <head> section that 
     contains a non-empty <title> element. -->
<head>
  <title>My Fun Page</title>
</head>
<body>

  <p>Click the button to return the number of characters in the string "Hello World!".</p>
  <input id="id"> <!-- input elements don't have a closing tag -->
  
  <!-- Don't use HTML event attributes to bind JavaScript callbacks.
       Do your event binding in JavaScript -->
  <button>Try it</button>
  <p id="demo"></p>

<script>
  // This is the modern way to bind events:
  document.querySelector("button").addEventListener("click", myFunction);
  
  // Just get your element references once, not each time the function runs
  const demo = document.getElementById("demo");
  const input = document.getElementById("id");
  
  function myFunction() {
    // Variables are fine, but they don't help you when you
    // are only going to use their value once. In that case
    // just refer to what you need:
 
    if(input.value.length == 10) {
      // Don't use .innerHTML if you can help it as it has security
      // and performance implications. Since you aren't working with
      // any HTML anyway here, use .textContent
      demo.textContent = "Equal to 10"
    } else {
      demo.textContent = "Not equal to 10"
    }
  }
</script>
</body>
</html>

答案 2 :(得分:1)

这就是我要做的。

三元表达式对于初学者来说可能不太容易理解,但我喜欢它们。

<script>
  function myFunction() {
    const str = document.getElementById("id").value
    const message = str.length === 10 ? "Equal to 10" : "Not equal to 10"

    document.getElementById("demo").innerHTML = message
  }
</script>
相关问题