HTML 表单 onclick 事件不调用 javascript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12517735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML Form onclick event doesn't call javascript function
提问by TheSquad
I would like to create a dynamic form, adding inputs into the form by pressing a button (or an image) when I put the code directly on the onclick event
我想创建一个动态表单,当我将代码直接放在 onclick 事件上时,通过按下按钮(或图像)将输入添加到表单中
alert("Hello");
it works... however, it doesn't when I try to call a javascript function... Even If I call the simple function hello(); (as well with add() )
它有效......但是,当我尝试调用 javascript 函数时它不会......即使我调用简单的函数 hello(); (以及 add() )
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function add() {
var container = document.createElement("div");
container.innerHTML = "<input type='text' name='email'><br/>";
document.getElementById('emails').appendChild(container);
}
function hello() {
alert("Hello");
}
?</script>
</head>
<body>
<form id="myform" name="myform" action="valid.php" method="POST">
<div id="emails">
<input type='text' name='email' value=''/><br />
</div>
<img width="50px" src="myimage.jpg" onclick='add();'/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Anyone manage to spot why ?
任何人设法发现为什么?
采纳答案by Rafael de Souza
回答by thewebguy
I copied this into a nice little jsfiddle here http://jsfiddle.net/dr9hG/
我把它复制到一个漂亮的小 jsfiddle 在这里http://jsfiddle.net/dr9hG/
I also changed the name from just "email"
to "email[]"
so that you can access all of them by array on the page this submits to.
我还将名称从 just 更改为"email"
,"email[]"
以便您可以在提交到的页面上通过数组访问所有这些。