您的位置:首页 > Web前端 > JavaScript

利用js和html实现表单操作(onsubmit、onclick、submit等方法的异同)

2016-04-28 21:24 633 查看
最近在写利用python+flask搭建后台,在写到与前端交互的时候需要对form进行数据过滤,但是在写onsubmit方法的时候老是达不到自己想要的效果,所以百度了一下这几种方法异同,顺带研究了下onclick、onsubmit、submit集合函数之间的关系和区别。

下面的介绍是在http://blog.csdn.net/wguoyong/article/details/7461511看到的:
onsubmit
You can override this event by returning false in the event handler. Use this capability to validate data on the client side to prevent invalid data from being submitted to the server. If the event handler is called by the onsubmit attribute of the form object, the code must explicitly request the return value using the return function, and the event handler must provide an explicit return value for each possible code path in the event handler function.
The submit method does not invoke the onsubmit event handler.

submit
The submit method does not invoke the onsubmit event handler. Call the onsubmit event handler directly. When using Microsoft? Internet Explorer 5.5 and later, you can call the fireEvent method with a value of onsubmit in the sEvent parameter.


首先生成一个form

view source

print?

1
<
form
 
action
=
"#"
 
method
=
"POST"
 
name
=
"A"
 
onsubmit
=
"return
X();"
>
2
<
input
 
type
=
"text"
 
value
=
""
 
/>
3
<
input
 
onclick
=
"Y()"
 
type
=
"submit"
 
value
=
"提交"
 
/>
4
</
form
>
自己写X()、Y()函数,我们会发现,这几个函数的执行顺序

1) onclick: Y();

2) onsubmit: X();

3) submit();

也就是说

只要 onclick 未 return false 那么就继续执行 onsubmit

只要 onsubmit 未return false 那么表单就被提交出去了

另外一点写法上注意一定要 “return X();” 才能取得函数的返回值,否则只是调用函数,返回值未被传递

正确写法:

<input type=submit onclick=”return X();”>

//X() 返回false后,form的submit会被终止

错误写法:

<input type=submit onclick=”X()”>

//X() 返回false后未传递给onclick事件,form的submit会继续

结合在博客上看到的内容,我发现其实是我在写
onsubmit指向的函数漏掉return flase导致即使是错误表单信息也提交了上去,下面po代码。

<pre name="code" class="javascript"><script>
function X(){
var form = document.getElementById('add_form');
var content= document.getElementById('content');
num=content.value.length;
alert(num);
if (content.value=='')
{
alert("内容为空") ;
return false;

}
if(num > 200)
{
alert("内容过多");
return false;
}
return true;
}
</script>
表格:
<form id="add_form" class="input-group" action='/' method="post" onsubmit="return X();">
<input class="form-control" id="content" name="content" type="text" value="">
<span class="input-group-btn">
<button class="btn btn-primary" type="submit">添加</button> <button type="reset">重置</button>
</span>
</form>



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: