当jQuery 1.7遇上focus方法

简介: jQuery中有一个focus()方法能设置对象的焦点,在1.7以下的版本中,不管对象是不是disabed状态,这个方法都不会报错(只是当disabled时,设置焦点的代码无效),但在1.7版本中,如果对象是disabled状态,这时调用focus()方法时,会直接报异常: Error: Can't move focus to the control because it is invisible, not enabled, or of a type that does not accept the focus. 意思是:不可见或不可用的元素无法获取焦点。

jQuery中有一个focus()方法能设置对象的焦点,在1.7以下的版本中,不管对象是不是disabed状态,这个方法都不会报错(只是当disabled时,设置焦点的代码无效),但在1.7版本中,如果对象是disabled状态,这时调用focus()方法时,会直接报异常:

Error: Can't move focus to the control because it is invisible, not enabled, or of a type that does not accept the focus.

意思是:不可见或不可用的元素无法获取焦点。(特别提一下:IE9很NB,能自动识别这种情况,在IE9下不会报错,但是IE9以下的版本全挂。)

<!doctype html>
<html>
	<head>
	<title>测试</title>
	<script src="jquery-1.7.min.js" type="text/javascript"></script>
	<!--<script src="jquery-1.4.4.min.js" type="text/javascript"></script>-->
	<script type="text/javascript">
		function fnTest(){
			//try{
				$("#txt").focus();
			//}catch(e){}
		}		
	</script>
	</head>
	<body>
		<div>
			<input type="text" disabled="disabled" id="txt"/>
			<input type="text" id="txt2"/>
			<input type="button" value="Test" onclick="fnTest()"/>
		</div>
	</body>
</html>

虽然只是一个小变化,但是却很容易造成大杯具,特别是你的js代码,在focus()之后,还有其它很多事情要做时:)

建议:

如果一定要用最高版本的jQuery,最省事的办法莫过于在写xxx.focus()时,加一个try/catch,变成

try{xxx.focus();}catch(e){}

 

目录
相关文章
|
1天前
|
JavaScript 前端开发
jQuery - noConflict() 方法
jQuery - noConflict() 方法
20 9
|
1天前
|
XML JavaScript 前端开发
jQuery - AJAX get() 和 post() 方法
jQuery - AJAX get() 和 post() 方法
16 6
|
7天前
|
JavaScript 前端开发
jQuery - noConflict() 方法
jQuery - noConflict() 方法
15 6
|
5天前
|
JavaScript
jQuery 遍历 方法
jQuery 遍历 方法
15 3
|
6天前
|
JavaScript
jQuery 效果 方法
jQuery 效果 方法
11 4
|
15天前
|
JavaScript
jQuery Callback 方法
jQuery Callback 方法
24 15
|
6天前
|
JavaScript
jQuery 事件 方法
jQuery 事件 方法
18 3
|
7天前
|
缓存 JavaScript 前端开发
jQuery - AJAX get() 和 post() 方法
jQuery - AJAX get() 和 post() 方法
15 4
|
5天前
|
JSON 前端开发 JavaScript
jQuery AJAX 方法
jQuery AJAX 方法
13 1
|
8天前
|
JavaScript 前端开发
jQuery - AJAX load() 方法
jQuery - AJAX load() 方法
9 1