[英]Why addEventListener for form submit doesn't work?
Im getting hard to dealing with addEventListener "submit" to form.我越来越难以处理 addEventListener “提交”到表单。 Here is the script:这是脚本:
<html>
<head>
<title>Testing Hehe</title>
</head>
<body>
<form action="" method="post">
<input type="text" name="q" onclick="this.parentNode.submit();" />
<input type="submit" value="Testing" />
</form>
<script type="text/javascript">
console.log(document.readyState);
window.onload = function(){
console.log(document.readyState);
document.forms[0].addEventListener('submit',function(e){
e.preventDefault();
},false);
var form = document.createElement('form');
form.method= "post";
var input= document.createElement('input');
input.type = "text";
input.name = "test";
input.addEventListener('click',function(){
form.submit();
},false);
form.appendChild(input);
var input2= document.createElement('input');
input2.type = "submit";
input2.name = "sbt";
form.appendChild(input2);
form.addEventListener('submit',function(e){
alert("test");
e.preventDefault();
},false);
document.body.appendChild(form);
}
</script>
</body>
</html>
<?php
if($_POST){
print_r($_POST);
exit;
}
?>
From above script, I have succeded kill form submit event when submit button clicked, but when I change the submit trigger to other part, such as when textbox clicked, the "submit" event still post directly.从上面的脚本中,单击提交按钮时我已经成功杀死表单提交事件,但是当我将提交触发器更改为其他部分时,例如单击文本框时,“提交”事件仍然直接发布。 I don't understand why it is happened and how to fix this problem..我不明白为什么会发生这种情况以及如何解决这个问题..
Thank you for attention:-) And you r answer will be great for me:-)感谢您的关注:-) 而你 r 的回答对我来说会很棒:-)
Instead of using:而不是使用:
input.addEventListener('click',function(){
form.submit();
},false);
You could use:你可以使用:
input.addEventListener('click',function(){
input2.click();
},false);
Just make sure to move var input2= document.createElement('input');
只要确保移动var input2= document.createElement('input');
before it.在它之前。
Example: http://jsfiddle.net/niklasvh/wcpx4/示例: http://jsfiddle.net/niklasvh/wcpx4/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.