0

我在下面有这段代码,有不同的数据,在我正在处理的页面上重复了 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 根据 (43%) 中的数字更改div.strong p(311) 中的数字。div.kpaGraph p最干净的方法是什么?我应该全选$('div.kpaGraph p')然后使用each()还是应该创建一个函数并在所有函数上运行它?

谢谢!

4

3 回答 3

1

您可以使用以下内容来找到与.each()on结合使用的正确元素$('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 示例

于 2013-02-21T17:02:47.897 回答
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
});
于 2013-02-21T17:03:37.493 回答
0

像这样的东西也可能很干净:

$("div.strong p").text(function(index, text){
    return $(this).closest("div.kpaBottom").prev("div.kpaGraph").find("p").text();
});

这会将文本更改为Target: 43%您的示例中的文本。

于 2013-02-21T17:10:03.273 回答