【发布时间】:2010-10-15 13:44:08
【问题描述】:
我的问题和示例基于 Jason 在 this 问题中的回答
我试图避免使用eventListener,而只是在单击提交按钮时调用handleClick onsubmit。
我的代码完全没有任何反应。
为什么没有调用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>
编辑:
请不要将框架作为解决方案。
以下是我对代码所做的相关更改,这些更改会导致相同的行为。
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>
【问题讨论】:
-
如果表单元素没有
sandbox="allow-scripts"属性,那么这些方法都不会在现代浏览器中工作。 w3schools.com/Tags/att_iframe_sandbox.asp -
@MuhammadUmer - AFAIK,当您明确创建作为沙盒的 iframe 时,仅需要沙盒属性。如果您的 HTML iframe 不包含“沙盒”属性,或者您没有 iframe,那么这些限制如何生效?
-
FWIW,这个问答的寓意是“当它不工作时,从你的代码中删除一些东西,直到你找到什么工作,然后回到你的错误”。如果警报被简化为
alert("Favorite weird creature");,OP 会发现它有效(出现警报),然后就会知道他在...getRadioButtonValue(..)的语法中有一些问题。从有效到无效的连续迭代可能会将问题隔离到this["whichThing"]没有返回值。一个更简单的问答:将其替换为document.aye.whichThing。解决了。
标签: javascript html forms dom-events