Javascript计算文本区域中的剩余字符

我只是想在文本区域内输入时计算剩余的字符数。我对 Javascript 很陌生,我写了这段代码,但它不起作用,我也不知道为什么。


它不算什么。始终显示 0 / 300。


html文件中的代码:


<p>  <textarea name="Inhalt" id="Inhalt" placeholder="Ihre Nachricht..." rows="5" maxlength="300 

</textarea> </p>

    

<div id="the-count">

 <span id="current">0</span>

 <span id="maximum">/ 300</span>

</div>


<script src="textarea_count.js"></script>

textarea_count.js 中的代码:


$('textarea').onkeyup(function() {


var characterCount = $(this).val().length,

  current = $('#current'),

  maximum = $('#maximum'),

  theCount = $('#the-count');


current.textContent(characterCount);



if (characterCount < 100) {

current.css('color', '#666');

}

if (characterCount > 99 && characterCount < 140) {

current.css('color', '#6d5555');

}

if (characterCount > 139 && characterCount < 200) {

current.css('color', '#793535');

}

if (characterCount > 199 && characterCount < 250) {

current.css('color', '#841c1c');

}

if (characterCount > 249 && characterCount < 299) {

current.css('color', '#8f0001');

}


if (characterCount >= 300) {

maximum.css('color', '#8f0001');

current.css('color', '#8f0001');

theCount.css('font-weight','bold');


} else {

maximum.css('color','#666');

theCount.css('font-weight','normal');

}


  

});

*请注意,我从 html 部分删除了不重要的代码,因为它与 textarea 无关,只是没有必要考虑。


呼唤远方
浏览 116回答 1
1回答

繁星coding

我了解到您是 javaScript 的新手。但是在您的代码中,您将 jquery 与 javascript 混合在一起,因此会出现一些错误。.onkeyup(function()是一个javascript函数=on('keyup', function(){}在jquery中textContent是纯 javascript =text(在 jquery 中。另外,请在浏览器中检查开发者控制台。当某些东西不工作时,这是你首先要看的地方$('textarea').on('keyup',function(){&nbsp; var characterCount = $(this).val().length,&nbsp; &nbsp; current = $('#current'),&nbsp; &nbsp; maximum = $('#maximum'),&nbsp; &nbsp; theCount = $('#the-count');&nbsp; current.text(characterCount);&nbsp; if (characterCount < 100) {&nbsp; &nbsp; current.css('color', '#666');&nbsp; }&nbsp; if (characterCount > 99 && characterCount < 140) {&nbsp; &nbsp; current.css('color', '#6d5555');&nbsp; }&nbsp; if (characterCount > 139 && characterCount < 200) {&nbsp; &nbsp; current.css('color', '#793535');&nbsp; }&nbsp; if (characterCount > 199 && characterCount < 250) {&nbsp; &nbsp; current.css('color', '#841c1c');&nbsp; }&nbsp; if (characterCount > 249 && characterCount < 299) {&nbsp; &nbsp; current.css('color', '#8f0001');&nbsp; }&nbsp; if (characterCount >= 300) {&nbsp; &nbsp; maximum.css('color', '#8f0001');&nbsp; &nbsp; current.css('color', '#8f0001');&nbsp; &nbsp; theCount.css('font-weight', 'bold');&nbsp; } else {&nbsp; &nbsp; maximum.css('color', '#666');&nbsp; &nbsp; theCount.css('font-weight', 'normal');&nbsp; }});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><textarea name="Inhalt" id="Inhalt" placeholder="Ihre Nachricht..." rows="5" maxlength="300"></textarea><div id="the-count">&nbsp;<span id="current">0</span>&nbsp;<span id="maximum">/ 300</span></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript