我不确定这是否可能,所以如果我问不可能的事情,请告诉我,但我有一个JSP页面,其中包含一个绑定到Spring MVC模型的表单。我有一个按钮,单击该按钮时将div的内容存储在javascript变量中。表单包含在此div 中。然后,div 内容被替换为其他一些 HTML。这是 JSP 页面...
<input id="linkEntity" type="button" value="Link" />
<input id="storeDiv" type="button" value="store" />
<div id="div1">
<form:form id="form1" method="post" modelAttribute="model" action="${pageContext.servletContext.contextPath}/save">
<select name="ethnicity" >
<option value="">Please select</option>
<c:forEach items="${ethnicityList}" var="et">
<option value="${et.code}" <c:if test="${et.code == model.ethnicity}">selected="selected"</c:if>>${et.desc}</option>
</c:forEach>
</select>
</form:form>
</div>
<script type="text/javascript">
$( document ).ready(function() {
var origDiv = "";
$("body").on("click", "#storeDiv", function() {
origDiv = $("#div1").html();
$("#div1").html("replace div with other contents..");
});
$("body").on("click", "#linkEntity", function() {
$("#div1").html(origDiv );
});
});
</script>
我想发生的是,如果说在 select 元素中进行了选择,我可以以某种方式记录并在我用原始 HTML 替换div 内容时选择该值吗?
$( document ).ready(function() {
var origDiv = $("#div1").html();
$("body").on("click", "#storeDiv", function() {
$("#div1").html("replace div with other contents..");
});
$("body").on("click", "#linkEntity", function() {
$("#div1").html(origDiv );
});
});
这是一个解决方案...在页面加载时创建另一个名为 formselections 的空 js 变量。
var formselections = "";
在原始 html 存储在 js 变量中的点,使用 ..
formselections = $("#form1").serializeArray();
然后,当您将原始 html 放回容器中时,迭代此变量,将表单元素设置为记录的值,如下所示。
$.each(formselections, function(i, e) {
$("#form1 [name="+e.name+"]").val(e.value);
});