jQuery高级技巧——DOM操作篇

来源:互联网 发布:星际2 天梯数据查询 编辑:程序博客网 时间:2024/06/10 01:22
 
回到顶部

页面加载之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!');});function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}

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

回到顶部

根据特定页面的执行对应的代码

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

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

复制代码
var route = {        _routes: {}, // The routes will be stored here        add: function(url, callback) {            this._routes[url] = callback;        },        run: function() {            jQuery.each(this._routes, function(pattern) { // pattern 指向_routes对象集合的key,即url                if (location.href.match(pattern)) {                    // "this" points to the function to be executed                    this(); //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:

<div id="elem"></div>

JS:

复制代码
// 变量保存jQuery对象var elem = $('#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:

<div id="elem"></div>

JS:

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

使用$()函数的第二个参数

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

复制代码
<ul id="firstList" >      <li>one</li>      <li>two</li>      <li>three</li></ul><ul id="secondList" >      <li>blue</li>      <li>green</li></ul>
复制代码

作用一:

//选取一个元素,通过#firstList限制元素只能在当前的ul节点范围内选取$('li' , '#firstList' ). each(function(){    console.log($(this). html());});//相当于$('#firstList' ). find('li' );

作用二:

复制代码
//创建一个元素。第二个参数为对应的配置属性,包含jQuery方法会被执行var div = $('<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

复制代码
// 需要解析的URLvar url = 'http://tutorialzine.com/books/jquery-trickshots?trick=12#comments' ;// 通过url创建一个新的链接var a = $('<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

作者:燎原之火
出处:http://www.cnblogs.com/bigboyLin/
本文链接:http://www.cnblogs.com/bigboyLin/p/4737042.html
本文版权归作者和博客园共有,欢迎转载,须保留此段声明,并给出原文链接,谢谢!
如果阅读了本文章,觉得有帮助,欢迎点击右下角推荐
分类: JavaScript
0 0
原创粉丝点击