jquery - 分割和计算字符?

发布于 12-11 04:52 字数 725 浏览 1 评论 0原文

我试图根据特定字符拆分字符串,然后计算每个部分中的字符数。有办法做到这一点吗?

所以,我有:

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
   });
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

睫毛溺水了2024-12-18 04:52:50

你脑子里有太多的 jQuery:

var first = characters[0].length;
var second = characters[1].length;

characters 是一个 字符串 数组,而不是 jQuery 对象。字符串没有 .text() 方法,它们已经是文本了。只需访问它们的 length 属性即可。

You have too much jQuery in your mind:

var first = characters[0].length;
var second = characters[1].length;

characters is an array of strings, not jQuery objects. Strings don't have a .text() method, they are already text. Just access their length property.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文