2012-08-03 25 views
0

我有這樣的腳本:從東西可變jquery:如何從htmlstring獲取值?

<script> 
    var stuff = '<input id="testinput" name="testinput" type="text" value="this is the right one" /><input id="testinput2" name="testinput2" type="text" value="this is the wrong one" />' 
</script> 

如何,我可以用jQuery獲得價值(「這是錯誤的一個」)?

回答

3
var stuff = '<input id="testinput" name="testinput" type="text" value="this is the one" /><input id="testinput2" name="testinput2" type="text" value="this is the wrong one" />'; 

console.log($(stuff).val()); // This is the one 

Demo

console.log($($(stuff)[1]).val());​ // This is the wrong one 
+0

和如何獲取的價值「,這是錯誤的「? – user603007 2012-08-03 06:43:06

+0

@ user603007已更新 – 2012-08-03 17:25:12

4

使用.val方法。

var value = $(stuff).val(); 

更新: 沒有注意到有一個在您的字符串多個輸入。 在這種情況下,您需要使用.map方法將值作爲數組返回。

The demo.

var stuff = '<input id="testinput" name="testinput" type="text" value="this is the one" /><input id="testinput2" name="testinput2" type="text" value="this is the wrong one" />'; 

console.log($(stuff).map(function() { 
    return $(this).val(); 
}));​ 
+0

以及如何獲得「這是錯誤的」值? – user603007 2012-08-03 06:43:12

+0

@ user603007檢查我的更新。 – xdazz 2012-08-03 06:50:06

0

使用val()用於獲取值,或者如果你是一個屬性之後使用.attr()

var v = $(stuff).val(); 

var attr = $(stuff).attr('attribute you want'); 
+0

以及如何獲得「這是錯誤的」值? – user603007 2012-08-03 06:43:27