jQuery的:如何从HTMLString获取价值?

use*_*007 0 jquery jquery-selectors

我有一个像这样的脚本:

<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>
Run Code Online (Sandbox Code Playgroud)

如何使用jQuery从stuff变量获取值(“这是错误的”)?

Ric*_*ann 6

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
Run Code Online (Sandbox Code Playgroud)

演示

console.log($($(stuff)[1]).val());? // This is the wrong one
Run Code Online (Sandbox Code Playgroud)


xda*_*azz 5

使用.val方法。

var value = $(stuff).val();
Run Code Online (Sandbox Code Playgroud)

更新: 没有注意到您的字符串中有多个输入。在这种情况下,您需要使用.map方法将值作为数组返回。

演示。

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();
}));?
Run Code Online (Sandbox Code Playgroud)