开发者

problem with .attr() method for getting value of attributes of elements

i have a string like this :

string_data = "<option value='1'>ahmad</option><option value='2'>mohammad</option><option value='3'>ali</option>"

now i want get the value of value attribute of options and alert it. for this i write this :

$(string_data).contents()
.each(function(){
    value   =   $(this).attr('value');
    text    =   $(this).text();
    alert(value);
});

but this code return undefined for all of them .

in Addition string_data is a string that i get it from a php 开发者_如何学运维script with Ajax via $.post() jQuery method.

i am using jquery 1.6 .


The contents() method retrieves the children of your elements which in your case are the text nodes. Omit that method call to iterate through <option> elements:

$(string_data).each(function(){
    value   =   $(this).attr('value');
    text    =   $(this).text();
    alert(value);
});


I'm not sure it's valid to load the string_data like this, when jQuery expects an identifier. It should probably be more like:

$('#some_hidden_select').html(string_data).find("option")
.each(function(){
    value   =   $(this).attr('value');
    text    =   $(this).text();
    alert(value);
});


Try:

$(string_data).find("option")
.each(function(){
    value   =   $(this).attr('value');
    text    =   $(this).text();
    alert(value);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜