我可以使用 html() 保存动态表单而不是遍历 INPUT 吗?

Can I save dynamic form with html() rather than iterating through INPUTs?

本文关键字:遍历 INPUT 表单 动态 可以使 html 保存 我可以      更新时间:2023-09-26

我有一个动态创建的HTML页面,它添加了输入。

我希望能够使用 html() 函数捕获页面(和所有表单输入值)。

不过,这似乎不起作用。 以以下页面为例:

<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$( document ).ready(function() {
        $( "#_create" ).click(function() {
            var myHtml = '<input class="my-input" val="">';
            $('#_input').html(myHtml);
        });
        $( "#_save" ).click(function() {
            alert($('#_masterDiv').html());
        });
        $( "#_saveIterate" ).click(function() {
            $("input").each(function(){
                alert(this.value);
            });
        });
    });
</script>
</head>
<body>
    <button id="_create">Create Dynamic Input</button><br>
    <button id="_save">Save by grabbing html</button><br>
    <button id="_saveIterate">Save by iterating</button><br>
    <div id="_masterDiv">
        <div id="_input">Input button here</div><br>
    </div>
</body>
</html>

单击"通过抓取 html 保存"会获取表单,但不获取值。单击"通过迭代保存"获取输入的值。

我是否需要调用"应用更改"之类的函数才能在 INPUT 中获取最新值?

某些浏览器(如 Firefox/Chrome)不会保存 HTML 输入值的当前状态。因此,您必须手动分配输入值:

$( document ).ready(function() {
        $( "#_create" ).click(function() {
            var myHtml = '<input class="my-input" value="">';
            $('#_input').html(myHtml);
        });
        $( "#_save" ).click(function() { 
         //if you have many input fields, loop through them all           
            $("input").each(function(){                
                //set the value manually
                this.setAttribute('value', this.value);                
            });            
            alert($('#_masterDiv').html());
        });
        $( "#_saveIterate" ).click(function() {
            $("input").each(function(){
                alert(this.value);
            });
        });
    });

这是jsfiddle链接:http://jsfiddle.net/urspz/1/