Jquery .text()。长度计数元素的代码以及字符? [英] Jquery .text().length counting element's code as well as characters?

查看:68
本文介绍了Jquery .text()。长度计数元素的代码以及字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检测div中的字符数量,如果少于5则执行某些操作:

  var n = $(#mydiv)。text()。length; 
if(n< 5){
//做点什么
}

但'n'似乎在计算自己使用的代码:

 < div id = mydiv > 

< / div>

所以即使div中没有​​字符: n = 23



有没有人知道一种方法来调整它只计算div本身内的字符?

 <$ div $ c > var n = $ .trim($(#mydiv)。text())。length; //使用String.trim()如果你想支持IE9 + 

演示:小提琴




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()。长度计数元素的代码以及字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆