[英]Why do my DOM changes disappear when I click a form button?
This is my first post, so consider me a n00b. 这是我的第一篇文章,所以考虑我为n00b。
I have created a simple form to access a value stored in a javascript array. 我创建了一个简单的表单来访问存储在javascript数组中的值。 I am trying to append an element to display the proper value. 我正在尝试附加一个元素以显示正确的值。 The logic works, my result will show, but only briefly, before it is overwritten. 逻辑有效,我的结果将被覆盖,但只会短暂显示。 Can you help? 你能帮我吗?
html html
<form>
<input type="text" label = "sitex" id="site"><br>
<input type = "submit" value = "Submit" onclick="getFormData(document.getElementById('site').value)">
</form>
<div id = "result"><p>Results:</p></div>
<script type="text/javascript" src="logic.js"></script>
javascript javascript
var results = "";
function getFormData(val1) {
var pw = {
"site1": "xyzabc",
"site2": "defghi",
"site3": "jklmno",
"site4": "pqrstu",
"site5": ["id1", "vwxyza"],
"site6": ["id2", "bcdefg"],
"site7": "hijklm",
"site8": ["id3", "nopqrs"],
"site8": ["id4", "tuvwxy"],
"site9": ["id5", "zabcde"],
"site10": "fghijk",
"site11": ["id6", "lmnopq"],
"site12": "rstuvw"
};
results = pw[val1];
showResults(results);
}
function showResults(val2) {
var div = document.createElement('div');
var pss = document.createTextNode(val2);
div.style.color = "red";
div.appendChild(pss);
document.getElementById("result").appendChild(div);
}
You're actually submitting your form when you click the Submit button and page is reloading. 当您单击“提交”按钮并且页面正在重新加载时,您实际上是在提交表单。 Just change the type of button from submit
to button
: 只要改变按钮的类型,从submit
到button
:
<input type="button" value="Submit" onclick="getFormData(document.getElementById('site').value)">
Pass your Javascript function 2 arguments, the first is the event object, the second is the value you are passing. 传递您的Javascript函数2个参数,第一个是事件对象,第二个是您要传递的值。 You can then use this to prevent the default behavior of a form (which is to submit the form and refresh the page) 然后,您可以使用它来防止表单的默认行为(即提交表单并刷新页面)
<form>
<input type="text" label = "sitex" id="site"><br>
<input type = "submit" value = "Submit" onclick="getFormData(event, document.getElementById('site').value)">
<div id = "result"><p>Results:</p></div>
<script type="text/javascript" src="logic.js"></script>
then in your javascript, prevent the default behavior with .preventDefault(); 然后在您的JavaScript中,使用.preventDefault()防止默认行为;
var results = "";
function getFormData(event, val1) {
event.preventDefault();
var pw = {
"site1": "xyzabc",
"site2": "defghi",
"site3": "jklmno",
"site4": "pqrstu",
"site5": ["id1", "vwxyza"],
"site6": ["id2", "bcdefg"],
"site7": "hijklm",
"site8": ["id3", "nopqrs"],
"site8": ["id4", "tuvwxy"],
"site9": ["id5", "zabcde"],
"site10": "fghijk",
"site11": ["id6", "lmnopq"],
"site12": "rstuvw"
};
results = pw[val1];
showResults(results);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.