jQuery高级技巧——DOM操作篇_Android, Python及开发编程讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  Android, Python及开发编程讨论区 »
总帖数
2
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 2304 | 回复: 1   主题: jQuery高级技巧——DOM操作篇        下一篇 
_chen
版主
等级:中校
经验:2139
发帖:39
精华:0
注册:2013-8-23
状态:离线
发送短消息息给_chen 加好友    发送短消息息给_chen 发消息
发表于: IP:您无权察看 2015-8-19 10:04:08 | [全部帖] [楼主帖] 楼主

页面加载之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');
// 判断是否为div
elem.is('div') && console.log("it's a divquot;);
// 是否包含类名.bigbox
elem.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 divnbsp&= $('<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

// 需要解析的URL
var 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


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




赞(0)    操作        顶端 
lei.zhang
注册用户
等级:少校
经验:989
发帖:7
精华:0
注册:1970-1-1
状态:离线
发送短消息息给lei.zhang 加好友    发送短消息息给lei.zhang 发消息
发表于: IP:您无权察看 2015-8-19 22:08:33 | [全部帖] [楼主帖] 2  楼

比较实用,谢谢楼主了 北京联动北方科技有限公司



赞(0)    操作        顶端 
总帖数
2
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论