下面的HTML
<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
$('.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/
3 2 1 6 当我有这个html时,但是
<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
为什么它不正确地还给我,请帮我修好它!
发布于 2011-12-18 14:10:44
您必须使用find或children来选择当前上下文中的元素。另外,使用parseInt(.., 10)解析数字。
演示:
$('.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)选择元素。这提高了效率。
演示:
$('.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);
});发布于 2011-12-18 14:10:33
http://jsfiddle.net/hQzZQ/24/
$('.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);
});https://stackoverflow.com/questions/8552258
复制相似问题