Jquery .text().length 计数元素和字符的代码? [英] Jquery .text().length counting element's code as well as characters?
本文介绍了Jquery .text().length 计数元素和字符的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想检测一个 div 中的字符数量,如果少于 5 个就做一些事情:
var n = $("#mydiv").text().length;如果 (n <5){//做点什么}
但 'n' 似乎在计算用于 div 本身的代码:
所以即使 div 中没有字符:n = 23
.
有谁知道一种方法可以将其调整为仅计算 div 本身内的字符数?
解决方案
修剪文本以排除文本中的前导和尾随空格
var n = $.trim($("#mydiv").text()).length;//如果你想支持IE9+,请使用String.trim()
演示:小提琴
I want to detect the amount of characters in a div and do something if there is less then five:
var n = $("#mydiv").text().length;
if (n < 5){
//do something
}
But 'n' seems to be counting the code used for the div it self:
<div id="mydiv">
</div>
So even if there are no characters within the div: n = 23
.
Does anyone know a way to adjust this to only count characters within the div itself?
解决方案
Trim the text to exclude the leading and trailing spaces in the text
var n = $.trim($("#mydiv").text()).length; //use String.trim() if you want to support IE9+
Demo: Fiddle
这篇关于Jquery .text().length 计数元素和字符的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文