我的JavaScript代码有问题,您可以在下面看到。
因此,当用户键入某些内容时,代码将对某些文本区域中的字符进行计数并实时对其进行计数。根据符号计数,用户有两个信息:
问题是,代码仅在我们键入至少一个符号时才开始。但是在我的网站上,此文本区域中有一些信息,这些信息是在页面加载时从数据库中加载的,因此文本区域中已经具有一些符号。但是,如我所说,计数功能在页面加载时不会启动,我们需要键入(或删除)至少一个符号。
我知道,以为我的代码应该行得通,因为我使用了onkeyup事件。但是,我也尝试使用onload事件。还尝试添加window.onload = countDescriptionChar(this)
; 脚本代码
但这仍然行不通。
因此,我需要在页面加载时(当我们没有按下任何键时)启动脚本,并保存在用户按下某个键时实时计数字符的功能。
我想我做错了...
你下面有我所有的代码
感谢帮助!
这是我使用的JavaScript代码
function countDescriptionChar(val) {
var len = val.value.length;
if ((len >= 0) && (len < 105)) {
$('#symbolsDescription').text(len);
document.getElementById("statusDescription").innerHTML = "<span style='color: orangered'>less then 105 characters</span>";
}
else if ((len >= 105) && (len <= 135)) {
$('#symbolsDescription').text(len);
document.getElementById("statusDescription").innerHTML = "<span style='color: green'>Idealy! (105 - 135 characters)</span>";
}
else {
$('#symbolsDescription').text(len);
document.getElementById("statusDescription").innerHTML = "<span style='color: orangered'>Too much... (more then 135)</span>";
}
};
然后是我在模板中使用的HTML代码。我使用Laravel在数据库的textarea中显示数据
<label for="" class="mt-4">Description</label>
<div id="statusDescription"></div>
Symbols: <div class="seocount" id="symbolsDescription"></div>
<textarea class="form-control" id="meta_description" name="meta_description" onkeyup="countDescriptionChar(this)" >
@isset ($article->meta_description)
{{ $article->meta_description}}
@endisset
</textarea>
查看您的代码,我添加了两件似乎可以完成您期望的事情:
添加$(document).ready(countDescriptionChar())
到您的JS代码中;
添加一个三元运算符,该三元运算符将在您分配len
var时查找您的参数,如果它返回为“ undefined”,则应查找您的id<textarea>
并收集其值
var len = val === undefined吗?document.getElementById('meta_description')。value.length:val.value.length
$(document).ready(countDescriptionChar())
function countDescriptionChar(val) {
var len = val === undefined ?
document.getElementById('meta_description').value.length :
val.value.length
if ((len >= 0) && (len < 105)) {
$('#symbolsDescription').text(len);
document.getElementById("statusDescription").innerHTML = "<span style='color: orangered'>less then 105 characters</span>";
}
else if ((len >= 105) && (len <= 135)) {
$('#symbolsDescription').text(len);
document.getElementById("statusDescription").innerHTML = "<span style='color: green'>Idealy! (105 - 135 characters)</span>";
}
else {
$('#symbolsDescription').text(len);
document.getElementById("statusDescription").innerHTML = "<span style='color: orangered'>Too much... (more then 135)</span>";
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="" class="mt-4">Description</label>
<div id="statusDescription"></div>
Symbols: <div class="seocount" id="symbolsDescription"></div>
<textarea class="form-control" id="meta_description" name="meta_description" onkeyup="countDescriptionChar(this)" >
@isset ($article->meta_description)
{{ $article->meta_description}}
@endisset
</textarea>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句