单击表单按钮时,为什么我的DOM更改会消失?

时间:2016-11-07 18:31:41

标签: javascript html forms button

这是我的第一篇文章,所以请考虑我一个n00b。

我创建了一个简单的表单来访问存储在javascript数组中的值。我试图附加一个元素来显示正确的值。逻辑有效,我的结果会在被覆盖之前显示,但只是简单地显示。你能帮忙吗?

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

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);
}

2 个答案:

答案 0 :(得分:4)

当您单击“提交”按钮并且页面正在重新加载时,您实际上是在提交表单。只需将按钮类型从submit更改为button

即可
<input type="button" value="Submit" onclick="getFormData(document.getElementById('site').value)">

答案 1 :(得分:0)

传递你的Javascript函数2个参数,第一个是事件对象,第二个是你传递的值。然后,您可以使用它来防止表单的默认行为(即提交表单并刷新页面)

J=0.05; B=0.02; Tload[t_]:=0.0; R1=2; \[Alpha]=30*\[Pi]/180; d=0.05;
g=0.001; Nturns=200; \[Mu]0=4*\[Pi]*10^-7; r=0.03; lm=0.02; d=0.1;
W=Sqrt[2*r^2-2*r^2*Cos[2*\[Alpha]]]; Rgmax=g/(\[Mu]0*r*d); Rm=lm/(\[Mu]0*W*d);
square[x_, x1_, x2_]:=UnitStep[x-x1]*(1-UnitStep[x-x2]);
Rg[\[Theta]_]:=Rgmax/((2 \[Alpha]-Mod[\[Theta],\[Pi]])*square[Mod[\[Theta],
  \[Pi]],-2 \[Alpha], 2 \[Alpha]] +(2 \[Alpha]-Mod[-\[Theta],\[Pi]])*
  square[Mod[-\[Theta],\[Pi]],-2 \[Alpha], 2 \[Alpha]]);
L[\[Theta]_] := Nturns^2/(2*Rg[\[Theta]]+Rm)*(square[Mod[\[Theta],\[Pi]],
  -2 \[Alpha],2 \[Alpha]]+square[Mod[-\[Theta],\[Pi]],-2 \[Alpha], 2 \[Alpha]]);

Plot[L[\[Theta]], {\[Theta],-8 \[Alpha],8 \[Alpha]}, PlotRange->All, PlotPoints->200]

<form>
<input type="text" label = "sitex" id="site"><br>
<input type = "submit" value = "Submit" onclick="getFormData(event, document.getElementById('site').value)">

然后在你的javascript中,使用.preventDefault();

防止默认行为
<div id = "result"><p>Results:</p></div>
<script type="text/javascript" src="logic.js"></script>