javascript jQuery:获取 HTML 以及输入值

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

jQuery: Get HTML as well as input values

javascriptjqueryhtml

提问by Ivan

I'm trying to have a variable store the HTML in a div tag, but simply using var a = $('div').html()doesn't store the values of the input tags that lie within the div.

我试图让一个变量将 HTML 存储在 div 标签中,但只是使用var a = $('div').html()不会存储位于 div 内的输入标签的值。

So, my question is, how should I go about saving the HTML andthe selected options and values of input tags to a variable using jQuery?

所以,我的问题是,我应该如何使用 jQuery将 HTML以及输入标签的选定选项和值保存到变量中?

Here is some example code:

下面是一些示例代码:

HTML:

HTML:

<div>
  <p>Some Text</p>
  <select name="word">
    <option value="1">Placeholder 1</option>
    <option value="2">Placeholder 2</option>
  </select>
  <input type="text" />
</div>

Javascript:

Javascript:

/* "a" should also have the user values, such that when I use $('body').append(a), 
it has the same user input as the div. */

var a = $('div').html(); 

Thanks in advance.

提前致谢。

回答by Sampson

You could $.clone()the element.

你可以$.clone()的元素。

var $a = $("div:first").clone();

$a.appendTo("body"); // Clone invades your body

Online Demo: http://jsbin.com/obebov/edit

在线演示:http: //jsbin.com/obebov/edit

回答by Azfar Niaz

You may also achieve this by first changing the value of input fields uding DOM like this:

您也可以通过像这样首先更改使用 DOM 的输入字段的值来实现此目的:

$('div input').each(function(){
    $(this).keyup(function(){
        $(this).attr('value',$(this).val());
    });
});

after which you can extract the HTML by using this:

之后,您可以使用以下方法提取 HTML:

$('div').html();