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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12008234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:03:22  来源:igfitidea点击:

Set value of input html string with jquery

javascriptjquery

提问by Doo Dah

I have snippet of HTML in a string like this:

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

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

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

我如何使用 jQuery 设置它的值,以便 HTML 像这样结束:

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

Thanks, Scott

谢谢,斯科特

采纳答案by Diode

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

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

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

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

EDIT :

编辑 :

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

您可以使用@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);

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($("<div>").append($htmlString).html());

回答by Curt

You would first need to add your element to the DOM (ie to your web page). For example:

您首先需要将您的元素添加到 DOM(即添加到您的网页)。例如:

$(".container").append(htmlString);

Then you can access your inputas a jquery object and add the value attribute like so:

然后,您可以将您的input作为 jquery 对象访问并添加 value 属性,如下所示:

$("#someID").val("newValue");

-- See Demo --

-- 见演示 --

回答by indot_brad

You just want to manipulate the string, right? There are a lot of ways to skin this cat, but

你只是想操纵字符串,对吧?有很多方法可以给这只猫剥皮,但是

var newString = htmlString.replace('>', ' value="newValue">');

回答by Shreedhar

After the dom ready, append your input to body and then grab the input with id = "someID" and set its value to newValue

在 dom 准备好后,将您的输入附加到 body 中,然后使用 id = "someID" 获取输入并将其值设置为 newValue

   $(document).ready(function(){
       $("body").append(htmlString);
       $("#someID").val("newValue");
    });