我的问题和例子基于杰森的回答this https://stackoverflow.com/questions/662630/javascript-form-bypassing-default-behaviour-for-ajax/664938#664938问题
我试图避免使用eventListener
,只是为了打电话handleClick
onsubmit
,当单击提交按钮时。
我的代码绝对不会发生任何事情。
Why is handleClick
没有被召唤?
<html>
<head>
<script type="text/javascript">
function getRadioButtonValue(rbutton)
{
for (var i = 0; i < rbutton.length; ++i)
{
if (rbutton[i].checked)
return rbutton[i].value;
}
return null;
}
function handleClick(event)
{
alert("Favorite weird creature: "+getRadioButtonValue(this["whichThing"]));
event.preventDefault(); // disable normal form submit behavior
return false; // prevent further bubbling of event
}
</script>
</head>
<body>
<form name="myform" onSubmit="JavaScript:handleClick()">
<input name="Submit" type="submit" value="Update" onClick="JavaScript:handleClick()"/>
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>
</body>
</html>
edit:
请不要建议框架作为解决方案。
以下是我对代码所做的相关更改,这些更改导致相同的行为。
function handleClick()
{
alert("Favorite weird creature: "+getRadioButtonValue(document.myform['whichThing'])));
event.preventDefault(); // disable normal form submit behavior
return false; // prevent further bubbling of event
}
</script>
</head>
<body>
<form name="aye">;
<input name="Submit" type="submit" value="Update" action="JavaScript:handleClick()"/>
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>
您可以使用 javascript url 形式
<form action="javascript:handleClick()">
或者使用 onSubmit 事件处理程序
<form onSubmit="return handleClick()">
在后面的表单中,如果你从handleClick返回false,它将阻止正常的提交过程。如果您希望浏览器遵循正常的提交过程,则返回 true。
由于以下原因,按钮中的 onSubmit 事件处理程序也会失败Javascript:
part
EDIT:我刚刚尝试了这段代码,它有效:
<html>
<head>
<script type="text/javascript">
function handleIt() {
alert("hello");
}
</script>
</head>
<body>
<form name="myform" action="javascript:handleIt()">
<input name="Submit" type="submit" value="Update"/>
</form>
</body>
</html>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)