首页
学习
活动
专区
圈层
工具
发布

.each增值
EN

Stack Overflow用户
提问于 2011-12-18 14:08:00
回答 2查看 60关注 0票数 0

下面的HTML

代码语言:javascript
复制
<div class="commentlinks">
    <a class="commentlinked blogcount">3</a>
    <a class="commentlinked fbcount">2</a>
    <a class="commentlinked disqcount">1</a>
    <a class="allcommentcount"></a>
</div>

用这个jQuery

代码语言:javascript
复制
$('.commentlinks').each(function() {
var currentValue = parseInt($(".blogcount").text());
var currentValue2 = parseInt($(".fbcount").text());
var currentValue3 = parseInt($(".disqcount").text());
var newValue = currentValue + currentValue2 + currentValue3;
$(".allcommentcount").text(newValue);
});

返回此成功的http://jsfiddle.net/hQzZQ/22/

代码语言:javascript
复制
   3     2     1     6   

当我有这个html时,但是

代码语言:javascript
复制
<div class="commentlinks">
    <a class="commentlinked blogcount">3</a>
    <a class="commentlinked fbcount">2</a>
    <a class="commentlinked disqcount">1</a>
    <a class="allcommentcount"></a>
</div>

<div class="commentlinks">
    <a class="commentlinked blogcount">7</a>
    <a class="commentlinked fbcount">6</a>
    <a class="commentlinked disqcount">1</a>
    <a class="allcommentcount"></a>
</div>

它返回http://jsfiddle.net/hQzZQ/23/

3 2 1 74 7 6

为什么它不正确地还给我,请帮我修好它!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-12-18 14:10:44

您必须使用findchildren来选择当前上下文中的元素。另外,使用parseInt(.., 10)解析数字。

演示:

代码语言:javascript
复制
$('.commentlinks').each(function() {
    var $this = $(this);
    var currentValue = parseInt($this.find(".blogcount").text(), 10);
    var currentValue2 = parseInt($this.find(".fbcount").text(), 10);
    var currentValue3 = parseInt($this.find(".disqcount").text(), 10);
    var newValue = currentValue + currentValue2 + currentValue3;
    $this.find(".allcommentcount").text(newValue);
});

如果文档结构良好,还可以使用.children("a")查找元素,然后使用.eq(..).slice(.., 1)选择元素。这提高了效率。

演示:

代码语言:javascript
复制
$('.commentlinks').each(function() {
    var $anchors = $(this).children("a"),
        currentValue = parseInt($anchors.eq(0).text(), 10),
        currentValue2 = parseInt($anchors.eq(1).text(), 10),
        currentValue3 = parseInt($anchors.eq(2).text(), 10),
        newValue = currentValue + currentValue2 + currentValue3;
    $anchors.eq(3).text(newValue);
});
票数 1
EN

Stack Overflow用户

发布于 2011-12-18 14:10:33

http://jsfiddle.net/hQzZQ/24/

代码语言:javascript
复制
$('.commentlinks').each(function() {
var currentValue = parseInt($(".blogcount",this).text());
var currentValue2 = parseInt($(".fbcount",this).text());
var currentValue3 = parseInt($(".disqcount",this).text());
var newValue = currentValue + currentValue2 + currentValue3;
$(".allcommentcount",this).text(newValue);
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8552258

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档