我过去一直使用这个没有任何问题。我似乎无法弄清楚这次出了什么问题;也许我只需要第二眼。
这是我的HTML代码:
<form id="myForm">
<table>
<tr>
<th>Product</th>
<th>Price</th>
</tr>
<tr>
<td>2014 HK Army Hardline Paintball Jersey</td>
<td>$89.95</td>
</tr>
<tr>
<td>Planet Eclipse 2013 Distortion Gloves</td>
<td>$34.95</td>
</tr>
<tr>
<td>Eclipse Geo 3.5 Paintball Marker</td>
<td>$1,600.00</td>
</tr>
</table>
<p>How many Paintball Jerseys would you like to order?</p>
<input id="jersey" type="number" value="0">
<p>How many Paintball Gloves would you like to order?</p>
<input id="gloves" type="number" value="0">
<p>How many Paintball Markers would you like to order?</p>
<input id="marker" type="number" value="0"><br>
<input type="button" onclick="submit()" value="Submit Form">
<input type="button" onclick="reset()" value="Reset Form"><br>
<p id="result"> </p>
</form>
我的JavaScript代码:
function submit() {
document.getElementById("result").innerText = "hi";
}
显然我用过&#34; hi&#34;作为测试。它没有显示我的光标位于p id =&#34;结果&#34;当我打开网站时。任何建议都表示赞赏。
编辑:我知道它是document.getElementById("result").innerText = "hi";
,但我也尝试过.innerHTML
,但仍然没有。
答案 0 :(得分:4)
您看到此问题是因为您使用的是内联事件处理程序。 The scope of inline event handlers is a bit tricky
长话短说:你根本没有打电话给submit
功能。
<form>
DOM元素的方法在内联事件处理程序的范围内。因此,在事件处理程序中,submit
不是指您的用户定义函数,而是指代并调用myForm.submit
,从而提交表单。
您可以通过与document.getElementById('myForm').submit
(检查控制台)进行比较来轻松测试。
function submit() {
// doesn't matter what's here
}
&#13;
<form id="myForm">
<input type="button" onclick="console.log('DOM element submit', submit === document.getElementById('myForm').submit);" value="Click me!">
</form>
&#13;
您可以renaming the function或not using inline event handlers修复此问题。
答案 1 :(得分:0)
试一下
将您的函数名称更改为other,然后提交例如submit2():
<form id="myForm">
<table>
<tr>
<th>Product</th>
<th>Price</th>
</tr>
<tr>
<td>2014 HK Army Hardline Paintball Jersey</td>
<td>$89.95</td>
</tr>
<tr>
<td>Planet Eclipse 2013 Distortion Gloves</td>
<td>$34.95</td>
</tr>
<tr>
<td>Eclipse Geo 3.5 Paintball Marker</td>
<td>$1,600.00</td>
</tr>
</table>
<p>How many Paintball Jerseys would you like to order?</p>
<input id="jersey" type="number" value="0">
<p>How many Paintball Gloves would you like to order?</p>
<input id="gloves" type="number" value="0">
<p>How many Paintball Markers would you like to order?</p>
<input id="marker" type="number" value="0"><br>
<input type="button" onclick="submit2()" value="Submit Form">
<input type="button" onclick="reset()" value="Reset Form"><br>
<p id="result"> </p>
</form>
<script type="text/javascript">
function submit2(){
document.getElementById("result").innerHTML = "hi";
}
</script>
我希望这会对你有所帮助。