I'm trying to find a way to loop through a list with Jquery, and if a certain class has text of "Not Complete", replace the words "Not Complete" with a animated gif.
Here's the list:
开发者_如何学编程<ul>
<li class="name">Name</li>
<li class="job">This</li>
<li class="status">Not Complete</li>
</ul>
The list is populated via a php script.
I tired this from another example here, but couldn't get it to work:
function change(){
if($('.status').text=='Not Complete')
{$('.status').replaceWith('<img src='loading.gif' />');}
else{}
}
$(function() {
$(".status").each(change);
});
Any idea's of how I could get this working?
If the .status
elements just have short text snippets (not long paragraphs of text), it should be safe to use the contains-selector
[docs].
$('li.status:contains(Not Complete)').html("<img src='loading.gif' />");
Notice that I alternated the quotation marks in the HTML. You used only single quotes, which was terminating the string prematurely.
I also added the element-selector
[docs] since :contains()
is not a standard selector. This will speed things up because now it will only have to look at <li>
elements.
Working example: http://jsfiddle.net/PahVB/1/
You forgot to call the text()
function:
$('.status').text() == ...
Your code checks whether the function itself is equal to 'Not Complete'
.
If the list is populated by PHP, why not just make PHP put it in there in the first place?
But if you're sticking with the jQuery, it should be text()==, not just text==.
Hmm - you need to rewrite this a little as you are currently running a loop, but then within the loop querying the collection again with if($('.status')
Try this:
$(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>
Maybe give this a try
The each function typically passes a parameter for index and object of the array you are iterating over. In your function you reselect the array each time. Try something like:
$(".status").each(function(index, value) {
if ($(this).text()=="Not Complete")
{
$(this).replaceWith($("<img />").attr("src","loading.gif"));
}
}
This is based on the jQuery documentation for the each function http://api.jquery.com/each/
精彩评论