javascript - 使用 jquery 设置输入 html 字符串的值

标签 javascript jquery

我在这样的字符串中有一段 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/

相关文章:

javascript - 将事件附加到对象/数组

javascript - 无法将元素附加到 FormData

javascript - 使用 React 渲染多个图表

javascript - CSS:如何防止网格中出现空单元格(通过删除部分空行)

javascript - Django Channels Websockets 立即连接和断开连接

javascript - JQuery 获取 XML 的一部分

javascript - JQuery .extend() 和 Javascript 类

jquery - 更新现有 jQuery 对象的选项

javascript - 检查nodejs路径是否存在

javascript - 如果另一个数组被修改,则数组被修改