是否可以通过.html()函数获取具有更新值属性的表单的html?
(简化)HTML:
<form>
<input type="radio" name="some_radio" value="1" checked="checked">
<input type="radio" name="some_radio" value="2"><br><br>
<input type="text" name="some_input" value="Default Value">
</form><br>
<a href="#">Click me</a>
Run Code Online (Sandbox Code Playgroud)
jQuery:
$(document).ready(function()
{
$('a').on('click', function() {
alert($('form').html());
});
});
Run Code Online (Sandbox Code Playgroud)
这是我想要做的一个例子:http: //jsfiddle.net/brLgC/2/
更改输入值并按"click me"后,它仍然返回带有默认值的HTML.
如何通过jQuery简单地获取更新的HTML?
如果你真的必须有HTML,你需要手动更新"value"属性:http: //jsfiddle.net/brLgC/4/
$(document).ready(function()
{
$('a').on('click', function() {
$("input,select,textarea").each(function() {
if($(this).is("[type='checkbox']") || $(this).is("[type='checkbox']")) {
$(this).attr("checked", $(this).attr("checked"));
}
else {
$(this).attr("value", $(this).val());
}
});
alert($('form').html());
});
});
Run Code Online (Sandbox Code Playgroud)
RGraham的答案对我不起作用所以我把它修改为:
$("input, select, textarea").each(function () {
var $this = $(this);
if ($this.is("[type='radio']") || $this.is("[type='checkbox']")) {
if ($this.prop("checked")) {
$this.attr("checked", "checked");
}
} else {
if ($this.is("select")) {
$this.find(":selected").attr("selected", "selected");
} else {
$this.attr("value", $this.val());
}
}
});
Run Code Online (Sandbox Code Playgroud)