Javascript 为每一个增加价值
下面的HTML 成功返回此文件 3. 2. 1. 6. 但是当我有这个htmlJavascript 为每一个增加价值,javascript,jquery,html,Javascript,Jquery,Html,下面的HTML 成功返回此文件 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> <
<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>
32174
76174
为什么它不正确地返回请帮我修复它
您必须使用find
或children
来选择当前上下文中的元素。另外,使用parseInt(..,10)
解析数字
演示:
如果文档结构良好,也可以使用.children(“a”)
查找元素,然后使用.eq(..)
或.slice(..,1)
选择元素。这提高了效率
演示:
使用find的解决方案不好。改用上下文@RoyiNamir$(“选择器”,this)
等于和大于$(this)。查找(“选择器”)
。如果文档的结构与问题中的结构完全相同,则应使用children()
。@RobW从您发布的链接中写道:“在内部,选择器上下文是用.find()方法实现的,因此$('span',this)相当于$(this).find('span')。Royi的解决方案字符更少,更易于阅读。我不想卷入性能辩论,但在本例中,使用.find可能不会给他买任何东西,但是parseInt(文本,10)是解析他的数字的安全方法
$('.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);
});
<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>
$('.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);
});
$('.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);
});
$('.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);
});