多个Divs多个单词计数器
对于我的WordList网站,我试图为每个列表进行自动单词计数器。我能够计算一个列表的单词,但是当我添加更多计数器时,计数器计数所有列表。我在任何地方都找不到解决方案,因此非常感谢所有帮助。
JSFIDDLE链接:
$(function() {
var text = $('.input').text();
var wordsCount = text.split(',').length;
$('.output').html('word count:' + wordsCount);
});
<span class="input">
These, are, 7, words, as, a, demonstration
</span>
<br>
<br>
<span class='output'></span>
<br>
<br>
<span class="input">
These, are, 7, words, as, a, demonstration
</span>
<br>
<br>
<span class='output'></span>
<script type = "text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要使用。每个元素循环循环
You need to use .each to loop through each element
虽然您已经接受了答案,但我认为我会借此机会向您展示另一种方法,并加强了一个事实,即您肯定必须迭代各种元素,但您 not 却不需要使用
每个()
进行此操作。另外,我选择了一种简单的JavaScript方法来解决完全相同的问题,以证明尽管jQuery提供了一些句法糖,并且抽象摘要JavaScript的一些冗长方面,但JavaScript本身就采用了JQuery的一些方法,但仍采用了JQuery的一些方法,但和方法。
也就是说,该守则的解释在下面对该代码的评论中:
JS小提琴演示。
参考:
css:
clamp()
。>。
类型
javaScript:
element.closest.closest.closest.closest()
。emelta >
。
event> event
。nodelist.prototype.prototype.prototype.foreach()
。
。< split()
jQuery:
crectest()
。。
find()
。。
next()
。。
on()
prev()
。。
text> text()
。。
While you've already accepted an answer, I thought I'd take the opportunity to show you an alternative approach, and reinforce the fact that – while you certainly have to iterate over the various elements – you don't need to use
each()
to do so.Also, I opted to show a plain JavaScript approach to solving the exact same problem in order to demonstrate that although jQuery offers some syntactic sugar, and abstracts away some of the verbose aspects of JavaScript, JavaScript has, itself, adopted some of jQuery's approach, and methods.
That said, the explanation of the code is in the comments to that code, below:
JS Fiddle demo.
References:
CSS:
attr()
.box-sizing
.clamp()
.:empty
.:last-of-type
JavaScript:
Element.closest()
.Element.nextElementSibling
.Element.querySelectorAll()
.Event
.EventTarget.addEventListener()
.NodeList.prototype.forEach()
.Node.textContent
.String.prototype.split()
.jQuery:
closest()
.find()
.next()
.on()
.prev()
.text()
.