jQuery iterate over table elements
I am trying to retrieve data from an img element inside a html web page using jQuery.
I know from the start that there is only 1 image but when I run the following code, I get 2 alert boxes. They contain the same information..
Does anyone know what i am doing wrong?
$("#tableX td").find("img").each(function() {
if ($(this).data("apple") == "orange") {
alert($(this开发者_开发百科).attr("src"));
}
});
Thanks.
UPDATE:
DOM output..
<td id="tdP4" align="center" style="border-top-width: 2px; border-right-width: 2px; border-bottom-width: 2px; border-left-width: 2px; border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; border-top-color: rgb(201, 201, 201); border-right-color: rgb(201, 201, 201); border-bottom-color: rgb(201, 201, 201); border-left-color: rgb(201, 201, 201); "><img id="imgP4" src="/images/t/00.jpg" style="border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; width: 63px; height: 103px; display: block; background-color: rgb(71, 7, 79); " alt="00"></td>
There are two possible reasons:
- Either you have several rows containing an image (the selector selects all images in the whole table)
- or the code is run twice.
maybe try a more specific selector
$("#tableX td > img").each(function() {
if ($(this).data("apple") == "orange") {
alert($(this).attr("src"));
}
});
EDIT: your <img>
tag is left open
You say
only one table, one td per tr, and 1 image!
This allows for multiple tr
elements, each with a td
and an img
inside.
The $("#tableX td").find("img").each
will find all img
elements inside the #tableX
. It doesn't matter if they are in different rows (tr
).
精彩评论