我正在嘗試做一個函數來計算剩餘的字符數。我想用addEvenetListener
監聽事件類型:附加addEventListener時不要調用事件
var output = document.getElementById('output');
\t var tweetTxt = document.getElementById("tweettext");
\t var charCount = 10;
\t var tweetTxt = document.getElementById("tweettext");
\t function textCounter(){
\t \t console.log("it works");
\t \t var count = charCount - document.getElementById("tweettext").value.length;
\t \t
\t \t if(count < 0){
\t \t \t output.classList.add("red");
\t \t \t output.classList.remove("black");
\t \t \t console.log("Less than zero");
\t \t }else{
\t \t \t output.classList.add("black");
\t \t \t output.classList.remove("red");
\t \t }
\t \t output.innerHTML = count + " characters left";
\t }
\t
tweetTxt.addEventListener('onKeyDown', textCounter, false);
tweetTxt.addEventListener('onKeyUp', textCounter, false);
tweetTxt.addEventListener('onChange', textCounter, false);
<div class="container">
\t <div class="row">
\t \t <div>
\t \t \t <textarea name="tweettext" id="tweettext">
\t \t \t \t
\t \t \t </textarea>
\t \t </div>
\t \t <div id="output" class="black">
\t \t \t
\t \t </div>
\t </div>
</div>
出於某種原因,這是行不通的。但是,當我附上聽衆<textarea>
元素它的工作原理:
var output = document.getElementById('output');
\t //var tweetTxt = document.getElementById("tweettext");
\t var charCount = 10;
\t var tweetTxt = document.getElementById("tweettext");
\t function textCounter(){
\t \t console.log("it works");
\t \t var count = charCount - document.getElementById("tweettext").value.length;
\t \t
\t \t if(count < 0){
\t \t \t output.classList.add("red");
\t \t \t output.classList.remove("black");
\t \t \t console.log("Less than zero");
\t \t }else{
\t \t \t output.classList.add("black");
\t \t \t output.classList.remove("red");
\t \t }
\t \t output.innerHTML = count + " characters left";
\t }
\t
/* tweetTxt.addEventListener('onKeyDown', textCounter, false);
tweetTxt.addEventListener('onKeyUp', textCounter, false);
tweetTxt.addEventListener('onChange', textCounter, false); */
<div class="container">
\t <div class="row">
\t \t <div>
\t \t \t <textarea name="tweettext" id="tweettext" onKeyUp="textCounter();" onKeyDown="textCounter();" onChange="textCounter();">
\t \t \t \t
\t \t \t </textarea>
\t \t </div>
\t \t <div id="output" class="black">
\t \t \t
\t \t </div>
\t </div>
</div>
所以,我在做什麼毛病以上addEvenetListener
方式?