jquery - 分割和计算字符?
我试图根据特定字符拆分字符串,然后计算每个部分中的字符数。有办法做到这一点吗?
所以,我有:
html
<a href="#" class="splitMe" title="Testing | this out">blah</a>
jquery
$(document).ready(function() {
$('.splitMe').each(function() {
var item = $(this).attr('title');
var characters = item.split("|");
// Here's where I get stuck...
// Tried various methods of length, but haven't been able to get it to work
// Most recent version that failed miserably...
var first = characters[0].text().length;
var second = characters[1].text().length;
alert(first+" "+second); //Yields characters[0] is not a function
});
});
I'm trying to split a string based on a particular character and then count the number of characters within each part. Is there a way to do this?
So, I have:
html
<a href="#" class="splitMe" title="Testing | this out">blah</a>
jquery
$(document).ready(function() {
$('.splitMe').each(function() {
var item = $(this).attr('title');
var characters = item.split("|");
// Here's where I get stuck...
// Tried various methods of length, but haven't been able to get it to work
// Most recent version that failed miserably...
var first = characters[0].text().length;
var second = characters[1].text().length;
alert(first+" "+second); //Yields characters[0] is not a function
});
});
你脑子里有太多的 jQuery:
characters
是一个 字符串 数组,而不是 jQuery 对象。字符串没有.text()
方法,它们已经是文本了。只需访问它们的length
属性即可。You have too much jQuery in your mind:
characters
is an array of strings, not jQuery objects. Strings don't have a.text()
method, they are already text. Just access theirlength
property.