button按钮在IE6、7、8、9、10中处理方式并不相同[转]

时间:2023-03-09 16:08:03
button按钮在IE6、7、8、9、10中处理方式并不相同[转]

http://msdn.microsoft.com/en-us/library/ms534696%28v=vs.85%29.aspx

转自:http://my.oschina.net/fz04003/blog/102085

以前的项目中,一值都是只考虑IE6、7、8+FF的,今天因为测试组有个小MM的电脑是使用的Win7的64位+IE10的,所以发现代码中有个奇怪的问题,代码如下:

html
<from action="a.php" method="post" name="testFrom" id="testFrom">
新增荣誉证书:<input type="text" name="certname" value="" maxlength="20"/>
<input type="hidden" name="submitFlag" value="1"/>
<button class="savebtn" onclick="return save_cert()"/>
</from>

js
function save_cert(){
//必要的验证
$("#testFrom").submit();
return false;
}

上面的代码,在FF、IE8等浏览器上表现都是正常的,但是在IE10会奇怪的出现两次提交现象。经过仔细的调试,发现需要修改button的默认类型为button才能在IE10下只做一次提交。就是说button需要这样写:

<button type="button" class="savebtn" onclick="return save_cert()"/>

猜测,IE10以前,button的默认类型时button,但是到10以后默认类型编程submit了,所以出现了两次提交。以后写代码的时候要注意了,使用button的时候要显式的指定type类型,根据需要进行处理。

备注:查了下微软的MSDN发现如下内容
http://msdn.microsoft.com/en-us/library/ms534696%28v=vs.85%29.aspx

A Submit button has the same default behavior as a button created by using the submit type with the input object. If the ENTER key is pressed while a user is viewing a form that contains a Submit button, the form is submitted. This default behavior of a Submit button is indicated by a border surrounding the button. The border appears when any control in the form receives the focus, other than another button. If the Submit button has a name property, the button contributes a name/value pair to the submitted data.

Windows Internet Explorer 8 and later. The default value of this attribute depends on the current document compatibility mode. In IE8 Standards mode, the default value issubmit. In other compatibility modes and earlier versions of Windows Internet Explorer, the default value isbutton.

看来其实微软在IE8就已经对这个做了修改,只不过我们一直使用的是兼容模式才没有注意到这一点啊。

补充说明<另外一个奇怪的现象>
如下代码:
<form name="searchForm" id="searchForm" method="get" action="action.php">
标题:<input type="text" name="title" id="title" value=""/>
类型:<select name="itype" id="itype">
<option value="0">全部</option>
<option value="1">类型1</option>
<option value="2">类型2</option>
</select>
<button type="submit" name="submit" id="submit">提交</button>
</form>
此时必须点击提交按钮表单才能提交,而使用form的提交事件则无效。
$("#itype").change(function(){
    $("#searchForm").submit();
});
这里$("#searchForm").submit();会执行,但是表单并不会提交。
必须要把button的type改成button才行,即button必须按如下方式编写:
<button type="button" name="button" id="button">提交</button>
不知道为什么?