我在这样的字符串中有一段 HTML:
var htmlString = '<input type="text" id="someID" name="someID">';
我如何使用 jQuery 设置它的值,以便 HTML 最终像这样:
'<input type="text" id="someID" name="someID" value="newValue">';
谢谢, 斯科特
最佳答案
$(htmlString).attr("value", "newValue");
但这将返回 jQuery 对象,而不是字符串。您可以将其添加到 DOM。
$(htmlString).attr("value", "newValue").appendTo("body"); // you can give any element instead of body
编辑:
您可以使用@idor_brad 的方法。那是最好的办法还是
var htmlString = '<input type="text" id="someID" name="someID">';
var $htmlString = $(htmlString);
$htmlString.attr("value1", "newValue1");
$htmlString.attr("value2", "newValue2");
$htmlString.attr("value3", "newValue3");
console.log($htmlString.get(0).outerHTML);
或
var htmlString = '<input type="text" id="someID" name="someID">';
var $htmlString = $(htmlString);
$htmlString.attr("value1", "newValue1");
$htmlString.attr("value2", "newValue2");
$htmlString.attr("value3", "newValue3");
console.log($("<div>").append($htmlString).html());
关于javascript - 使用 jquery 设置输入 html 字符串的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12008234/