Getting the Span id attribute Value in Jquery

2019-04-02 09:23发布

问题:

I have a "mytable" which contains "mytd" inturn contains the "Myspan" i want to get the .I want to get the "myspan_1" in jquery .How do i do that.

Small try here

$("#mytable").find('td > #span').attr("value","myspan_+i");

where "i" is an incrementing value

I coud not get Span id .All iam trying "id" value of span tag

回答1:

try these

$("#mytable").find("td > span").attr("id");

this will get the id of the current span. if you want to assign an id to the span you can do this.

$("#mytable").find("td > span").attr("id", "myspan_"+i");

where i is an incremental variable.

furthermore, if you are adding id to each td > span you can do a for loop or $.each() in all td of #mytable

var i=0;
$.each($("#mytable").find("td"), function(){
    $(this).find("span").attr("id", "myspan_"+i);
    i++;
});

Edit:

As I read your title i think I miss understood your question. But I think here's what you want. You want to get the value of the attribute Value in the element with id of #span actually if you are looking for an id in jquery, you can call it directly since id is always unique.

$("#span").attr("value", "myspan_"+i);

since i is an incremental value, you need to put it outside the quotes.

Edit 2:

To add value to an attribute value

$("#mytable").find("td > #span").attr("value", "myspan_"+i);

Edit 3:

Assuming your span id has an incremental myspan_1 which always starts at 1

var spanid = $("#mytable").find("td > span").attr("id", "myspan_"+i);
var idvalue = spanid.split('_')[1];

this will get the 1 of the myspan_1

or you could just directly get the i since i is the number that you want

var spanid = $("#mytable").find("td > span").attr("id", "myspan_"+i);
var idvalue = i;