使用jQuery,有条件地改变跨度的最快方法是什么?

leo*_*ora -1 jquery jquery-selectors

我在网页上有很多项目,如下所示:

<span id="Joe" class="Status">Pending</span>
<span id="Bill" class="Status">Completed</span>
<span id="Jonh" class="Status">Pending</span>
<span id="Scott" class="Status">Started</span>
Run Code Online (Sandbox Code Playgroud)

我想要一些jquery来改变每个具有"待定"的html()的跨度,然后将其更改为"已启动"或将其更改为该特定跨度的Id

作为选择器获得具有特定html值的所有跨度然后更改它们的最佳方式是什么?

Ror*_*san 7

用途:contains():

$('.Status:contains("Pending")').text('Started');
Run Code Online (Sandbox Code Playgroud)

或者,filter():

$('.Status').filter(function() {
    return $(this).text() == 'Pending';
}).text('Started');
Run Code Online (Sandbox Code Playgroud)

我会想象:contains选择器更快.您可以在JSPerf上自行检查

编辑 我自己做了测试.事实证明,至少filter():containsChrome 更快64%:http://jsperf.com/contains-vs-filter-rpm


如果我想要动态文本(特定跨度的属性)而不是硬编码"已开始"怎么办?

<span class="Status" data-new-text="Started">Pending</span>
<span class="Status" data-new-text="Started">Completed</span>
<span class="Status" data-new-text="Started">Pending</span>
<span class="Status" data-new-text="Started">Started</span>
Run Code Online (Sandbox Code Playgroud)
$('.Status').filter(function() {
    return $(this).text() == 'Pending';
}).each(function() {
    $(this).text($(this).data('new-text'));
};
Run Code Online (Sandbox Code Playgroud)