jquery循环遍历列表并替换

问题描述:

我试图找到一种方式来循环使用jquery的列表,如果某个类有文本“不完整”,用动画gif替换单词“不完整”。jquery循环遍历列表并替换

这里的名单:

<ul> 
<li class="name">Name</li> 
<li class="job">This</li> 
<li class="status">Not Complete</li> 
</ul> 

列表可通过PHP脚本填充。

我从这里另一个例子厌倦了,但不能得到它的工作:我怎么能得到这个工作

function change(){ 
if($('.status').text=='Not Complete') 
{$('.status').replaceWith('<img src='loading.gif' />');} 
else{} 
} 

$(function() { 
    $(".status").each(change); 
}); 

任何想法的?

如果.status元素只有简短的文本片段(不是很长的文本段落),那么使用contains-selector[docs]应该是安全的。

$('li.status:contains(Not Complete)').html("<img src='loading.gif' />"); 

请注意,我交替引号的HTML。您只使用了单引号,这会过早地终止字符串。

我还添加了element-selector[docs],因为:contains()不是标准选择器。这会加快速度,因为现在只需要查看<li>元素。


工作例如:http://jsfiddle.net/PahVB/1/

你忘了打电话的功能text()

$('.status').text() == ... 

你的代码检查功能本身是否等于'Not Complete'

如果该列表是由PHP居住,为什么不干脆让PHP把它放在那里摆在首位?

但是,如果你坚持使用jQuery,它应该是text()==,而不仅仅是文本==。

嗯 - 你需要重写这一点了,你正在运行一个循环,但随后内循环使用,如果($(”状态。)

试试这再次查询集合:

$(function() { 
     $(".status").each(function(){ 
      if($(this).text() == 'Not Complete'){ 
       $(this).replaceWith('<img src='loading.gif' />'); 
     }); 
}); 

<script> 
$(".status").each(function() 
{ 
    if($(this).text() == "Not Complete") 
    { 
     $(this).html("<img src='loading.gif' />"); 
    } 
}); 

</script> 

也许试试这个

的每个函数通常通行证你遍历数组的索引和对象的参数。在你的函数,你重新选择每次阵列。尝试一些东西一样:

$(".status").each(function(index, value) { 
    if ($(this).text()=="Not Complete") 
    { 
     $(this).replaceWith($("<img />").attr("src","loading.gif")); 
    } 
} 

这是基于jQuery的文档的每个功能http://api.jquery.com/each/