.attr()方法获取元素属性值的问题

时间:2011-05-27 08:12:13

标签: javascript jquery

我有一个这样的字符串:

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

现在我想获取选项的value属性的值并提醒它。对此,我写这个:

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

但是此代码会为所有这些代码返回 undefined 另外 string_data 是一个字符串,我通过$ .post()jQuery方法从Ajax的php脚本中获取它。
我正在使用jquery 1.6。

3 个答案:

答案 0 :(得分:3)

contents()方法检索元素的,在您的情况下是文本节点。省略该方法调用迭代<option>元素:

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

答案 1 :(得分:0)

尝试:

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

答案 2 :(得分:0)

当jQuery需要一个标识符时,我不确定加载这样的string_data是否有效。它应该更像是:

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