jQuery 计数字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9004095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery count characters
提问by lgt
I'm having problems to figure out why jquery string counter won't show me the expected result.
我在弄清楚为什么 jquery 字符串计数器不会向我显示预期结果时遇到问题。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
var count = $('h1').length;
alert(count);
</script>
</head>
<body>
<h1>some text</h1>
</body>
</html>
the result should be with this example 9, but instead I'm getting 0
结果应该是这个例子 9,但我得到的是 0
回答by Matt MacLean
$("h1") returns a jQuery object (in which the length property is the number of elements returned), and since you are calling it before the page is completely loaded it is actually retuning 0 elements.
$("h1") 返回一个 jQuery 对象(其中 length 属性是返回的元素数),并且由于您在页面完全加载之前调用它,它实际上正在重新调整 0 个元素。
What you want is:
你想要的是:
$(document).ready(function() {
var count = $("h1").text().length;
alert(count);
});
回答by Richard Dalton
You are getting 0 because the h1 hasnt loaded when the code has been run so firstly you need to put it inside a document.ready. This still won't give the answer you want as it will just tell you the number of h1 tags on the page. To get the answer you want you need to do:
你得到 0 因为当代码运行时 h1 还没有加载所以首先你需要把它放在一个 document.ready 中。这仍然不会给出您想要的答案,因为它只会告诉您页面上 h1 标签的数量。要获得您想要的答案,您需要执行以下操作:
$(document).ready(function() {
var count = $('h1').text().length;
alert(count);
});
回答by Marius Ilie
try this:
尝试这个:
$(document).ready(function(){
var count = $('h1').text().length;
alert(count);
})
回答by Zakiman Hamid
I use like this, done...
我是这样用的,完成...
$('#MEDIA_TUTORIAL_KATEGORI_DESCRIPTION').on('keyup',function() { var count = $(this).val().length; if(count>=150){ var textColor='text-danger'; }else{ var textColor='text-success'; } $('.counter').html(''+count+''); });
$('#MEDIA_TUTORIAL_KATEGORI_DESCRIPTION').on('keyup',function() { var count = $(this).val().length; if(count>=150){ var textColor='text-danger'; } else{ var textColor='text-success'; } $('.counter').html(''+count+''); });
$('#MEDIA_TUTORIAL_KATEGORI_DESCRIPTION').on('keyup',function() {
var count = $(this).val().length;
if(count>=150){ var textColor='text-danger'; }else{ var textColor='text-success'; }
$('.counter').html('<span class="'+textColor+'">'+count+'</span>');
});
回答by Eric Yin
<script type="text/javascript">
var count = $('h1').html().length;
alert(count);
</script>
$('h1')
is object, so the length is 0 (the first one, or the only one)
$('h1')
是对象,所以长度为0(第一个,或者唯一的)
you need to .html()
to get whats inside, then check length
你需要.html()
得到里面的东西,然后检查长度