表单提交期间onclick属性的不同行为

时间:2013-07-21 20:34:11

标签: javascript forms onclick jsfiddle

您好我遇到了一个关于表单提交的onclick属性的奇怪行为。

服务器页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head lang="en-us" >
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Return Form Example</title>
    <script type="text/javascript">
        function doSomething(){
            alert("hey");
            return false;
        }
    </script>
</head>

<body>
    <form action="submit.php" method="post">
        <input type="submit" onclick="return doSomething()" value="click me!">
    </form>
</body>
</html>

在这个例子中,在我的服务器上运行,当我点击提交按钮时,我得到一个警告说嘿,我留在当前页面。但是,我尝试在jsfiddle上设置相同的示例,我得到404错误,意味着表单已提交。我无法弄清楚为什么会这样。

这是我试图在我的服务器上复制行为的jsfiddle。

的jsfiddle: http://jsfiddle.net/46XSv/

2 个答案:

答案 0 :(得分:2)

您想要选中“no wrap - in <head>”选项,即“不要包装Javascript代码,将其放在部分中”。

选择“框架和扩展程序”

下的“no wrap - in <head>

在此页面中,您可以找到底部每个选项的说明:http://doc.jsfiddle.net/basic/introduction.html

最好在return语句的末尾加上分号,如下所示:

<input type="submit" onclick="return doSomething();" value="click me!">

答案 1 :(得分:1)

您应该使用onsubmit元素上的<form>而不是onclick元素上的<input>。它会正常工作。