我正在尝试根据特定字符拆分字符串,然后计算每个部分中的字符数。有没有办法做到这一点?
所以,我有:
<a href="#" class="splitMe" title="Testing | this out">blah</a>
$(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
});
});
答案 0 :(得分:10)
你脑子里有太多的jQuery:
var first = characters[0].length;
var second = characters[1].length;
characters
是一个字符串的数组,而不是jQuery对象。字符串没有.text()
方法,它们已经是文本。只需访问他们的length
财产。