Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/418.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用jquery设置输入html字符串的值_Javascript_Jquery - Fatal编程技术网

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

Javascript 使用jquery设置输入html字符串的值,javascript,jquery,Javascript,Jquery,我有一个字符串中的HTML片段,如下所示: var htmlString = '<input type="text" id="someID" name="someID">'; '<input type="text" id="someID" name="someID" value="newValue">'; var htmlString=''; 我如何使用jQuery设置它的值,使HTML以如下方式结束: var htmlString = '<input typ

我有一个字符串中的HTML片段,如下所示:

var htmlString = '<input type="text" id="someID" name="someID">';
'<input type="text" id="someID" name="someID" value="newValue">';
var htmlString='';
我如何使用jQuery设置它的值,使HTML以如下方式结束:

var htmlString = '<input type="text" id="someID" name="someID">';
'<input type="text" id="someID" name="someID" value="newValue">';
”;
谢谢,
Scott

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

$(".container").append(htmlString);
然后,您可以作为jquery对象访问
输入
,并添加value属性,如下所示:

$("#someID").val("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='';
变量$htmlString=$(htmlString);
$htmlString.attr(“value1”、“newValue1”);
$htmlString.attr(“value2”、“newValue2”);
$htmlString.attr(“value3”、“newValue3”);
log($htmlString.get(0.outerHTML);

var htmlString='';
变量$htmlString=$(htmlString);
$htmlString.attr(“value1”、“newValue1”);
$htmlString.attr(“value2”、“newValue2”);
$htmlString.attr(“value3”、“newValue3”);
console.log($(“”).append($htmlString.html());

在dom就绪后,将输入附加到body,然后使用id=“someID”获取输入并将其值设置为newValue

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

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

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

我知道。。。我想也许你已经找到了一个不使用DOM的聪明方法。哦:)是否要在不使用DOM的情况下检索最终字符串?这也有可能让我一路走到那里。如何从jQuery对象中获取HTML字符串?在我的例子中,这是最优雅的解决方案,因为我的HTML很复杂。