<p>优化后代码如下:</p>
<!DOCTYPE html>
<html>
<head>
  <title>汉字检测器</title>
  <meta charset="UTF-8">
  <style>
    /* 居中显示 */
    body {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100vh;
      margin: 0;
      background-color: #f7f7f7;
    }
<pre><code>h1 {
  font-size: 36px;
  font-weight: bold;
  margin-bottom: 20px;
}

.input-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 500px;
  height: 300px;
  padding: 20px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

.textarea {
  width: 100%;
  height: 200px;
  padding: 10px;
  font-size: 18px;
  border: 1px solid #ccc;
  border-radius: 5px;
  resize: none;
  margin-bottom: 20px;
}

.btn-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  background-color: #007bff;
  color: #fff;
  font-size: 18px;
  cursor: pointer;
  margin: 0 10px;
}

.clear-btn {
  background-color: #dc3545;
}

.output {
  margin-top: 20px;
  font-size: 18px;
  font-weight: bold;
}
</code></pre>
  </style>
</head>
<body>
  <h1>汉字检测器</h1>
  <div class="input-box">
    <textarea class="textarea" placeholder="请输入需要检测的汉字"></textarea>
    <div class="btn-wrap">
      <button class="btn check-btn">检测</button>
      <button class="btn clear-btn">清空</button>
    </div>
  </div>
  <div class="output"></div>
  <script>
    const textarea = document.querySelector('.textarea');
    const checkBtn = document.querySelector('.check-btn');
    const clearBtn = document.querySelector('.clear-btn');
    const output = document.querySelector('.output');
<pre><code>checkBtn.addEventListener('click', () =&gt; {
  const content = textarea.value.trim();
  const reg = /[\u4e00-\u9fa5]/g;
  const result = (content.match(reg) || []).length;
  output.innerText = `输入的文本中共包含 ${result} 个汉字`;
});

clearBtn.addEventListener('click', () =&gt; {
  textarea.value = '';
  output.innerText = '';
});
</code></pre>
  </script>
</body>
</html>
<p>优化内容:</p>
<ol>
<li>将输出信息添加到页面中,而不是每次都创建新的元素节点。</li>
<li>给输出信息添加样式,使其更加清晰明了。</li>
<li>优化清空按钮的逻辑,使其清空输出信息。</li>
</ol>
优化bug!DOCTYPE htmlhtmlhead	title汉字检测器title	meta charset=UTF-8	style		 居中显示 		body 			display flex;			flex-direction column;			align-items center;			justify-content center;			height 100vh;			margin 0;

原文地址: https://www.cveoy.top/t/topic/NlE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录