javascript 使用 jQuery 获取带有值的 html 元素(动态生成)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20178074/
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-27 17:56:52  来源:igfitidea点击:

Get html elements (dynamically generated) with values using jQuery

javascriptjqueryhtmldynamic

提问by Unknown

Is it possible using jQuery to get whole div content(dynamically generated elements) with values? For example, child element may be a div, span, select, or input?

是否可以使用 jQuery 获取带有值的整个 div 内容(动态生成的元素)?例如,子元素可能是 div、span、select 或 input?

I am trying to save whole div content(generated on fly) with values as .html file. I tried with one div which has form and input elements.

我正在尝试将整个 div 内容(动态生成)与值保存为 .html 文件。我尝试了一个具有表单和输入元素的 div。

HTML:

HTML:

<div id="inputs">
    <form class="mainForm">
        <div style="height: 100%;" id="div1">
                <label>Input1</label>
                <input type="text" id="input1" name="input1"/>
        </div>
    </form>
</div>
<input id="addform" type="button" value="Click to add Input"/>
<input id="getform" type="button" value="Click to get html"/>

jQuery:

jQuery:

$(document).ready(function(){
    $("input#addform").click(function(){
        $("div#inputs").append($('form.mainForm').clone().html());
    });

    $("input#getform").click(function(){
        alert($("div#inputs").clone().html());
    });
});

FIDDLE:

小提琴:

http://jsfiddle.net/UhJfn/

http://jsfiddle.net/UhJfn/

How to get whole div#inputscontent with values (entered by user) On click of Click to get htmlbutton?

如何div#inputs通过单击Click to get html按钮获取带有值(由用户输入)的全部内容?

Help would be appreciated.

帮助将不胜感激。

P.S: Here I used only one input in form. But in my real case, we do have select, span, image, etc.

PS:这里我只使用了一个表单输入。但在我的真实案例中,我们确实有选择、跨度、图像等。

回答by Rajaprabhu Aravindasamy

Try this,

试试这个,

You have to explicitly update the valueattribute to achieve your need.

您必须显式更新value属性才能满足您的需要。

$(document).ready(function(){

    $(document).on('keyup','input[type="text"]',function(){
        $(this).attr('value',$(this).val());
    });

    $("input#addform").click(function(){
        $("div#inputs").append($('form.mainForm').clone().html());
    });

    $("input#getform").click(function(){
        alert($("div#inputs").clone().html());
    });
});

DEMO

演示