子字符串方法不返回最大字符数限制

问题描述 投票:0回答:3

[当字符数超过最大限制(20个字符)时,substring方法将返回输入中从索引0到20的字符。substring方法将覆盖用户尝试输入的字符数超过20的所有内容。] >

但是在我的程序中,我可以在达到最大限制后输入更多字符。为什么会这样呢?我不希望这样。

const txt = document.querySelector('textarea')
const message = document.querySelector('.message')

let maxLength = 20;
let warnLength = 15;

['keyup', 'keydown', 'change'].forEach(event => {
  txt.addEventListener(event, textCounter)
})

function textCounter() {
  let count = txt.value.length
  if (count > warnLength) {
    message.innerHTML = `${(maxLength-count)} characters left`
  } else if (count > maxLength) {
    txt.value = txt.value.substring(0, maxLength)
  }
}
textarea {
  width: 400 px;
  height: 100 px;
}
<textarea></textarea>
<div class="message"></div>

[当字符数超过最大限制(20个字符)时,子字符串方法返回从索引0到20的输入中键入的字符。子字符串方法将覆盖所有内容...

javascript character counting
3个回答
1
投票
您可以只设置maxlength<textarea>属性,并完全消除代码的子字符串部分。

1
投票
if(count> warnLength){在字符15之后始终为true

0
投票
只需反转if条件:
© www.soinside.com 2019 - 2024. All rights reserved.