`
445822357
  • 浏览: 739360 次
文章分类
社区版块
存档分类
最新评论

锋利的jquery之快速定位

 
阅读更多

学习jquery有些时间了,感觉jquery的封装的特性特别出色,尤其是屏蔽了复杂的DOM操作,在以往的操作中,定位一个标记,总要想文档,树这些概念,但是在jquery中,只要和css一样的写法,就可以快速定位一个标记.

下面我们通过代码来看看是怎么定位的:

css定位的代码:


直接定位系统标签:

ul,li{
	margin:0px;
	padding:0px;
	list-style:none;
}


定位带有class的标签:

.Loading{
	width:400px;
	/*margin-left:auto;
	//margin-right:auto;*/
	margin:0 auto;
	visibility:hidden;
		
}


定位带有id属性的标签:

#contentsecond{
	width:300px;
	height:100px;
}



在jquery中定位这样的标签


定义带有ID属性的标签:

$("#realcontent").load("test.html");

直接定义系统标签及定义带有class属性的标签:

$("div.contentin").removeClass("contentin");



现在我们来看看用DOM找到一个标签:

	function setBorder( n )
	{
	document.getElementById( "image1" ).border = n;
	} 


现在我们看看jquery是如何帮助我们封装这个功能的:

	(function() { 
	var 
	// Will speed up references to window, and allows munging its name. 
	window = this, 
	// Will speed up references to undefined, and allows munging its name. 
	undefined, 
	// Map over jQuery in case of overwrite 
	_jQuery = window.jQuery, 
	// Map over the $ in case of overwrite 
	_$ = window.$, 
	jQuery = window.jQuery = window.$ = function(selector, context) { 
	// The jQuery object is actually just the init constructor 'enhanced' 
	return new jQuery.fn.init(selector, context); 
	}, 
	// A simple way to check for HTML strings or ID strings 
	// (both of which we optimize for) 
	quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/, 
	// Is it a simple selector 
	isSimple = /^.[^:#\[\.,]*$/; 
	jQuery.fn = jQuery.prototype = { 
	init: function(selector, context) { 
	// Make sure that a selection was provided 
	// Make sure that a selection was provided 
	selector = selector || document; 
	this[0] = selector; 
	this.length = 1; 
	this.context = selector; 
	return this; 
	}, 
	show:function() { 
	alert("this.show"); 
	}, 
	// Start with an empty selector 
	selector: "", 
	// The current version of jQuery being used 
	jquery: "1.3.2" 
	}; 
	jQuery.fn.init.prototype = jQuery.fn; 
	})(); 
	function test(src){ 
	alert($(src)); 
	$(src).show();

扩展:隐式迭代

下面是书中提到的一个jquery的特点

当用JQuery找到带有“.myClass”类的全部元素,然后隐藏他们时。无需循环遍历每一个返回的元素。相反,JQuery里的方法都被设计成自动操作的对象集合,而不是单独的对象,这使得大量的循环结构变得不再必要,从而大幅度地减少代码量。

实际是jquery将dom元素的树形结构,封装为一个集合,在给某类方法添加事件的时候,jquery代替我们遍历给他们都连接到代码段,这样就减少了我们很多的重复工作!

例子:

$(".yourclass").addClass("newclass");
像这样的就是隐式迭代因为$(".yourclass")选到的元素不一定只有一个,比如$(".yourclass")选中n个元素 这n个元素都会加上"newclas"这个class,除了ID选择器其它都是隐式迭代的比如$("#yourclass") 就算有多个id="yourclass" 也只能得到第1个在jqery中,因为它迭代的时候只取第一个元素!所有的方法都被设计成自动操作对象集合,而不是单一的一个对象,这样避免了大量的没有意义的循环

总结:

通过对代码的简单理解,我们不难发现,jquery简单的背后做了大量的总结及抽象工作,所以我们可以这么总结:
1,要向写好代码,必须不断优化改进!
2,要向做好软件,尽量灵活抽象是正道
3,一个团队的管理,犹如设计一个页面,快速定位某项工作的基础是有一个全局的管理观念(参考代码中的window)



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics