jQuery高级技巧——DOM操作篇

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: |||超大  

页面加载之DOMReady事件所谓domReady,也就是文档就绪,我们都知道,在操作dom时必须要在dom树加载完成后才能进行操作。如何检测DOM树已经构建完成,以下是一些实现的方式:

1.使用jQuery:

//with jQuery$(document).ready(function(){/*...*/});//shorter jQuery version$(function(){/*...*/});

2.监听DOMContentLoaded事件,DOM 树创建完成后会触发,不支持IE10以下版本。

//without jQuery (doesn't work in older IEs)document.addEventListener('DOMContentLoaded',function(){//your code goes here},false);

3.监听readyState状态,可实现跨浏览器

readyState 的状态属性:

"uninitialized" – 原始状态"loading" – 下载数据中"loaded" – 下载完成"interactive" – 还未执行完毕"complete" – 脚本执行完毕r(function(){

alert('DOM Ready!');

});functionr(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}

这个方法是不断监听readyState的loading状态,加载完成后则执行对应方法。具体可参考:http://www.dustindiaz.com/smallest-domready-ever

根据特定页面的执行对应的代码如果所有页面的代码都写在一个javaScript文件中,这样的代码就会难以维护。简单的办法就是根据不同的页面执行不同的代码。来看下例子:

例如在test.js有以下代码:

varroute ={

_routes: {},//The routes will be stored hereadd:function(url, callback) {this._routes[url] =callback;

},

run:function() {

jQuery.each(this._routes,function(pattern) {//pattern 指向_routes对象集合的key,即urlif(location.href.match(pattern)) {//"this" points to the function to be executedthis();//this 指向指向 _routes对象集合的value,即要执行的方法}

});

}

}//Will execute only on this page:route.add('test.html',function() {

alert('Hello there!');

});

route.add('PRoducts.html',function() {

alert("this won't be executed :(");

});//You can even use regex-es:route.add('.*.html',function() {

alert('This is using a regex!');

});

route.run();

使用逻辑与运算符利用逻辑与运算符可以简化条件分支语句写法,例子:

一般的写法:

//Instead of writing this:if($('#elem').length){//do something}

更好的写法:

$('#elem').length && alert("doing something");

非常有用的jquery is()方法is()方法非常有用,来看些例子:

HTML:

<divid="elem"></div>

JS:

// 变量保存jQuery对象varelem = $('#elem');//判断是否为divelem.is('div') && console.log("it's a div");//是否包含类名.bigboxelem.is('.bigbox') && console.log("it has the bigbox class!");//是否可见elem.is(':not(:visible)') && console.log("it is hidden!");//设置元素执行动画elem.animate({'width':200},1);//是否执行动画elem.is(':animated') && console.log("it is animated!");

定义一个exists函数判断一个jQuery对象是否存在需要判断length属性,可以封装为exists函数,简化代码,更加易读。

HTML:

<divid="elem"></div>

JS:

//一般方法console.log($('#elem').length == 1 ? "exists!" : "doesn't exist!");//封装方法jQuery.fn.exists =function(){returnthis.length > 0; }

console.log($('#elem').exists() ? "exists!" : "doesn't exist!");

使用$()函数的第二个参数$()函数可以接收两个参数,第二个参数的作用是什么,可以来看下例子:

<ulid="firstList"><li>one</li><li>two</li><li>three</li></ul><ulid="secondList"><li>blue</li><li>green</li></ul>

作用一:

//选取一个元素,通过#firstList限制元素只能在当前的ul节点范围内选取$('li' , '#firstList' ). each(function(){

console.log($(this). html());

});

//相当于$('#firstList' ). find('li' );

作用二:

//创建一个元素。第二个参数为对应的配置属性,包含jQuery方法会被执行vardiv = $('<div>',{"class" : "bigBlue","CSS": {"background-color" : "purple"},"width" : 20,"height" : 20,"animate" : {//使用jQuery的方法作为属性"width" : 200,"height" : 50}

});

div. appendTo('body' );

取消右键Click事件$(function(){

$(document).on("contextmenu" ,function(e){

e. preventDefault();

});

});

取消文本选中//适应于所有浏览器

$('p.descr' ). attr('unselectable' , 'on')

. css('user-select' , 'none')

. on('selectstart' ,false);

解析锚元素URL//需要解析的URLvarurl = 'http://tutorialzine.com/books/jquery-trickshots?trick=12#comments';//通过url创建一个新的链接vara = $('<a>',{ href: url });

console. log('Host name: ' + a. prop('hostname'));

console. log('Path: ' + a. prop('pathname'));

console. log('Query: ' + a. prop('search'));

console. log('Protocol: ' + a. prop('protocol'));

console. log('Hash: ' + a. prop('hash' ));

输出结果:

Host name: tutorialzine.com

Path: /books/jquery-trickshots

Query: ?trick=12

Protocol: http:

Hash: #comments

以上是一些知识总结,如有任何建议或疑问,欢迎留言讨论。

参考链接:

http://www.cnblogs.com/rubylouvre/p/4277408.html

http://www.dustindiaz.com/smallest-domready-ever

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航