我对 javascript 比较陌生,但现在我有一个可以通过单击 <button>
进行更改的表单。然后最后他们应该能够单击提交按钮来实际提交并保存表单。
所有其他按钮都会触发各自的 javascript 函数,但按下此按钮后应该会更改特定 <span id='planname'>
的innerHTML标签。
<td><span id=''></span><span id='planname'></span></td>
<td id='planopt'><button class='button square blue effect-2' onclick="changePlan('Myfixworked','change');">Change</button></td>
问题是当我单击此按钮时,它确实运行该功能:
function changePlan(x,action){
if(action == 'change'){
var id = 'planname';
document.getElementById(id).innerHTML = x;
}
}
它更改了该 id 的innerHTML,但紧接着,它提交了表单。我尝试重命名 id,它产生相同的结果。我什至尝试更改它触发的函数,它产生相同的结果。如果我更改 id,它会影响在此之后出现的任何 id,例如 var id = 'planopt';
,效果很好,更改了innerHTML并且不提交表单。
如有任何帮助,我们将不胜感激。综合代码如下。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function changePlan(x,action){
if(action == 'change'){
var id = 'nameofplan';
document.getElementById(id).innerHTML = x;
}
}
</script>
</head>
<body>
<form action='' method='post' name='quote'>
<table border='0' style='border-collapse:collapse;' width='100%' id='serviceplan'>
<tr style='border-bottom: 2px solid #3D3D3D;'><th align='left' colspan='2'>Description</th><th align='left' width='30%'>Quantity</th><th width='10%'>Price</th><th align='right' width='25%'>Total</th></tr>
<tr style='border-bottom: 1px solid #3D3D3D;'><td class='subt' colspan='5'>Service Plan</td></tr>
<tr style='border-bottom: 1px dotted #3D3D3D;'>
<td align='left'><span id='nameofplan'>Your Plan</span></td>
<td id='planopt'><button class='button square blue effect-2' onclick="changePlan('Your New Plan','change');">Change</button></td>
<td>1</td>
<td align='center'>$<span id='planprice'>1.00</span>/month</td>
<td align='right'>$<span id='subplan'>1.00</span></td>
</tr>
</table>
</form>
</body>
</html>
最佳答案
向按钮元素添加 type='button'
属性。默认情况下,表单元素中的按钮元素充当提交按钮。
使用 return false
或 preventdefault
是错误的方法,因为您只是抑制问题的症状(即您的按钮是提交按钮)。
关于javascript - onclick触发提交?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14144655/