textarea实时字符计数+预览不工作[重复]

问题描述 投票:-3回答:1

这个问题在这里已有答案:

我正在尝试使用纯JS没有Jquery来获取实时字符数+ textarea的实时预览,但是会出现一些错误。在这里我的代码

var wpcomment = document.getElementById('text');

wpcomment.onkeyup = wpcomment.onkeypress = function(){
    document.getElementById('DrevCom').innerHTML = this.value;
}
function count()
{
  var total=document.getElementById("text").value;
  total=total.replace(/\s/g, '');
  document.getElementById("total").innerHTML="Total Characters:"+total.length;
}
<textarea id="text" onkeyup="count();"  placeholder="Add comments:"></textarea>



<p id="total">Total Characters:0</p>
<div id="DrevCom"></div>
javascript html
1个回答
1
投票

您正在将HTML中的onkeyup属性设置为count(),然后使用Javascript覆盖它。你只能有一个onKeyup属性,所以要么使用event listener,要么让一个函数调用另一个。

var wpcomment = document.getElementById('text');

wpcomment.onkeyup = wpcomment.onkeypress = function(){
    document.getElementById('DrevCom').innerHTML = this.value;
    count()
}
function count()
{
  var total=document.getElementById("text").value;
  total=total.replace(/\s/g, '');
  console.log(total);
  document.getElementById("total").innerHTML="Total Characters:"+total.length;
}
<textarea id="text"  placeholder="Add comments:"></textarea>



<p id="total">Total Characters:0</p>
<div id="DrevCom"></div>
© www.soinside.com 2019 - 2024. All rights reserved.