我在下面的代码中有不同的数据,在我正在处理的页面上重复了10次以上:
HTML:
<div class="kpaGraph">
<p>Target: 43%</p>
<div class="progress">
<div class="bar"></div>
</div>
</div>
<div class="kpaBottom">
<div class="strong">
<p>311</p>
</div>
<div class="weak">
<p>number of teachers trained</p>
</div>
</div>
我希望使用Javascript / jQuery在此代码的所有实例中以相同的方式基于div.strong p
(43%)中的数字更改div.kpaGraph p
(311)中的数字。最干净的方法是什么?我应该选择所有$('div.kpaGraph p')
然后使用each()
还是应该创建一个函数并在所有函数上运行它?
谢谢!
答案 0 :(得分:1)
您可以使用以下内容与.each()
上的$('div.kpaGraph p')
一起找到合适的元素:
$(this).parent().next('div.kpaBottom').find('div.strong p')
例如,使用以下内容将获取kpaGraph p节点中的值,并将其附加到以下kpaBottom节点中的p节点:
$('div.kpaGraph p').each(function () {
$(this).parent().next('div.kpaBottom').find('div.strong p').html('foo');
});
<强> jsFiddle example 强>
答案 1 :(得分:0)
有几种方法。
您可以使用“下一步”。
$('.kpaGraph').each(function(){
var $kpaStrong = $(this).next('.kpaBottom .strong p');//this is the elm that has 311
});
或者你必须以某种方式在他们之间建立一种关系,这样你才能知道他们在一起,就像一个共同的父母一样。
<div class="kpaWr">
<div class="kpaGraph">
<p>Target: 43%</p>
<div class="progress">
<div class="bar"></div>
</div>
</div>
<div class="kpaBottom">
<div class="strong">
<p>311</p>
</div>
<div class="weak">
<p>number of teachers trained</p>
</div>
</div>
</div>
然后使用jQuery,您可以选择它:
$('.kpaGraph').each(function(){
var $kpaStrong = $(this).closest('.kpaWr').find('.kpaBottom .strong p');//this is the elm that has 311
});
答案 2 :(得分:0)
这样的事情也可能很干净:
$("div.strong p").text(function(index, text){
return $(this).closest("div.kpaBottom").prev("div.kpaGraph").find("p").text();
});
这会将示例中的文本更改为Target: 43%
。