0

我有一个这样的脚本:

<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 从 stuff 变量中获取值(“这是错误的”)?

4

4 回答 4

7

使用.val方法。

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

更新: 没有注意到您的字符串中有多个输入。在这种情况下,您需要使用.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();
}));​
于 2012-08-03T04:20:07.470 回答
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

演示

console.log($($(stuff)[1]).val());​ // This is the wrong one
于 2012-08-03T04:19:18.950 回答
0

用于val()获取值或如果您使用属性.attr()

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

var attr = $(stuff).attr('attribute you want');
于 2012-08-03T04:26:11.050 回答
0

在选择器失败之前,我遇到了类似的问题,直到我这样做:

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" />';

var myValue = HtmlElementAttribute(stuff, 'testinput2', 'value');

function HtmlElementAttribute(htmlString, elementId, attributeName) {
    var foundValue = '';
    $(htmlString).filter(function (x) {
        var idX = eval('$(htmlString)[x].id');
        if (idX && idX == elementId) {
            foundValue = $(eval('$(htmlString)[x].outerHTML')).attr(attributeName);
        }
    });
    return foundValue;
}
于 2018-04-12T15:15:59.043 回答