在这里,我正在练习将html与jQuery一起使用。我有一个表格要问有关您的汽车的问题。问题是一切正常,但是在重置表单后,它将删除刚刚添加的所有内容。
我调试了程序,它正在执行我想要的操作,但是一旦它停止执行“ writeHtml”,它所做的一切都会被清除。
<!DOCTYPE HTML>
<html>
<head>
<title> Sabio Practice </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
function writeHtml(){
var model = $("#Model").val();
var make = $("#Make").val();
var year = $("#Year").val();
var vin = $("#VIN").val();
$("#pp").html("<ul>")
$("#pp").html("<li>Make: " + make + "</li>" +
"<br/><li>Model: " + model + "</li>" +
"<br/><li>Year: " + year + "</li>" +
"<br/><li>VIN: " + vin + "</li>");
$("#pp").html("</ul>")
}
console.log("got here");
$("#Register").click(function(){
writeHtml();
$("#myForm")[0].reset();
});
});
</script>
</head>
<body>
<div>
<form id = "myForm" method = "get">
<input id = "Model" placeholder = "Model"><br>
<input id = "Make" placeholder = "Make"><br>
<input id = "Year" type = "number" placeholder = "Year"><br>
<input id = "VIN" placeholder = "VIN"><br>
<button id = "Register" name = "Register"> Register</button>
<button id = "Cancel" name = "Cancel">Cancel</button>
</form>
<p id = "pp">
</p>
</div>
</body>
</html>
我只希望对DOM所做的编辑是永久的。
答案 0 :(得分:1)
您还应该阻止默认行为,事件订阅应如下所示:
$("#Register").click(function(e) {
e.preventDefault();
writeHtml();
$("#myForm")[0].reset();
});
答案 1 :(得分:1)
您用html()
覆盖您的内容,最好使用append()
$("#pp").append("<ul>")
$("#pp").append("<li>Make: " + make + "</li>" +
"<br/><li>Model: " + model + "</li>" +
"<br/><li>Year: " + year + "</li>" +
"<br/><li>VIN: " + vin + "</li>");
$("#pp").append("</ul>")
并将按钮的类型设置为button
。否则,将提交表单。
<button type="button"></button>
答案 2 :(得分:1)
如果您未在表单中设置类型,则为提交; 因此您应该将按钮类型设置为按钮;
<button id = "Register" name = "Register" type="button"> Register</button>
答案 3 :(得分:0)
所以我有两个问题。一个是我第一次改写之后再次重写了innerhtml。
第二个问题是我没有为按钮指定类型。按钮的默认类型是“提交”,因为因此提交了我的表单,它会将我重定向到页面的新页面。
答案 4 :(得分:0)
<!DOCTYPE HTML>
<html>
<head>
<title> Sabio Practice </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
function writeHtml(){
var model = $("#Model").val();
var make = $("#Make").val();
var year = $("#Year").val();
var vin = $("#VIN").val();
var htmlText = "<ul>";
htmlText += `<li>Make: ${make}</li>
<br/>
<li>Model: ${model}</li>
<br/>
<li>Year: ${year}</li>
<br/>
<li>VIN: ${vin}</li>`;
htmlText += "</ul>"
$("#pp").append(htmlText);
}
console.log("got here");
$("#Register").click(function(e){
e.preventDefault();
writeHtml();
$("#myForm")[0].reset();
});
});
</script>
</head>
<body>
<div>
<form id = "myForm" >
<input id = "Model" placeholder = "Model"><br>
<input id = "Make" placeholder = "Make"><br>
<input id = "Year" type = "number" placeholder = "Year"><br>
<input id = "VIN" placeholder = "VIN"><br>
<button id = "Register" name = "Register"> Register</button>
<button id = "Cancel" name = "Cancel">Cancel</button>
</form>
<p id = "pp">
</p>
</div>
</body>
</html>