使用jquery设置输入html字符串的值 [英] Set value of input html string with jquery

查看:69
本文介绍了使用jquery设置输入html字符串的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这样的字符串中有HTML片段:

I have snippet of HTML in a string like this:

var htmlString = '<input type="text" id="someID" name="someID">';

如何使用jQuery设置其值,以便HTML最终如下:

How do I, with jQuery, set its value so that the HTML ends up like this:

'<input type="text" id="someID" name="someID" value="newValue">';

谢谢,
Scott

Thanks, Scott

推荐答案

$(htmlString).attr("value", "newValue");

但是这将返回jQuery对象,而不是字符串。您可以将其添加到DOM。

But this will return jQuery object, not string. You can add it to DOM.

$(htmlString).attr("value", "newValue").appendTo("body"); // you can give any element instead of body

编辑:

您可以使用@ idor_brad的方法。这是最好的方法或

You can use @idor_brad's method. That is the best way or

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());

这篇关于使用jquery设置输入html字符串的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆