使用jQuery获取填充表单的HTML代码

时间:2010-09-22 07:44:57

标签: javascript jquery html

我有一个包含不同控件的网页。我必须在按钮单击时获取html源代码,以获取具有值的特定div元素的控件。

jQuery .html()方法为我提供了没有值的html控件源,但是我需要带有用户选择值的html源代码。

1 个答案:

答案 0 :(得分:4)

尝试迭代每个<input>并在访问html之前将其value属性设置为其DOM值。

jsFiddle http://jsfiddle.net/AWK9S/3/

$('form input').each(function()
{
    this.setAttribute('value',this.value);
    if (this.checked)
        this.setAttribute('checked', 'checked');
    else
        this.removeAttribute('checked');
});

$('form select').each(function()
{
    var index = this.selectedIndex;
    var i = 0;
    $(this).children('option').each(function()
    {
        if (i++ != index)
            this.removeAttribute('selected');
        else
            this.setAttribute('selected','selected');
    });
});

$('form textarea').each(function()
{
    $(this).html($(this).val());
});

jsFiddle http://jsfiddle.net/AWK9S/3/