HTML5中类jQuery选择器querySelector的高级使用 document.querySelectorAll.bind(document);
基本用法
querySelector
该方法返回满足条件的单个元素。按照深度优先和先序遍历的原则使用参数提供的CSS选择器在DOM进行查找,返回第一个满足条件的元素。 ----> querySelector得到一个DOM
var element = document.querySelector('#container');//返回id为container的dom
var element = document.querySelector('div#container');//返回id为container的首个div
var element = document.querySelector('.foo,.bar');//返回带有foo或者bar样式类的首个元素
querySelectorAll
该方法返回所有满足条件的元素,结果是个nodeList集合。查找规则与前面所述一样。 ----> querySelectorAll 得到一个伪数组 DOM
var elements = document.querySelectorAll('div.foo');//返回所有带foo类样式的d<div id="box"> //surface blog
querySelectorAll支持属性操作 这个用也比较多
<div id="box" >
<ul>
<li data-href='http://www.qq.com'>tagname 111</li>
<li class="surfaces">这是clase 222</li>
<li class="surfaces">这是class 333</li>
<li class="surfaces" data-href='http://www.baidu.com'>这是class 444</li>
</ul> </div>
document.getElementById("box").addEventListener("click",function(){
var attr=document.querySelectorAll('[data-href]');
console.log(attr);
},!1);
移动端 getElementById(id), querySelector 和querySelectorAll 已经能够满足大部分dom操作需求了;
高级用法
先附上相关 html http://www.cnblogs.com/surfaces/
<div id="box">
<ul>
<li >tagname 111</li>
<li class="surfaces">这是clase 222</li>
<li class="surfaces">这是class 333</li>
<li class="surfaces">这是class 444</li>
</ul> </div>
先看看 querySelector的高级应用
var query = document.querySelector.bind(document); //单个的
var query_id=query('#box'); //dom id
var query_class=query('.surfaces'); // dom class
var query_tagname=query('li') //dom 标签
获取看到这里,你会怀疑 这都可以,我们跑一下代码看看 结果
console.log('query'+query_id.innerHTML); //
console.log('query'+query_class.innerHTML); //// 第一个 222
console.log('query'+query_tagname.innerHTML); //// 第一个 222 query_id.addEventListener('click',function(){
console.log('click_query_id'+this.innerHTML); //'click surfaces 2222
});
query_class.addEventListener('click',function(){
var e=e||window.event;
console.log('click_query_class'+this.innerHTML); //'click surfaces 2222
e.stopPropagation();
}); query_tagname.addEventListener('click',function(e){
var e=e||window.event;
console.log('click_query_tagname'+this.innerHTML); //'click surfaces 2222
e.stopPropagation();
});
上张图 看看控制台的结果
然后我们再看看 queryAelectorAll的高级用法
var $=queryAll = document.querySelectorAll.bind(document); //集合 个人感觉最犀利 surfaces
var $id=$('#box'); //id
var $class=$('.lione'); //class
var $tagname=$('li'); //tagName
跑一下这段代码看看
var $id=$('#box'); //id
var $class=$('.surfaces'); //class
var $tagname=$('li'); //tagName console.log('queryAll'+$id[0].innerHTML);
console.log('queryAll'+$class[0].innerHTML); //222
console.log('queryAll'+$tagname[0].innerHTML);//111 $id[0].addEventListener('click',function(){
console.log('click_queryAll'+this.innerHTML); //'click surfaces 2222
}); $class[0].addEventListener('click',function(e){
console.log('click_$class'+this.innerHTML); //'click surfaces 2222
e.stopPropagation();
}); $tagname[0].addEventListener('click',function(e){
console.log('click_$tagname'+this.innerHTML); //'click surfaces 2222
e.stopPropagation();
});
看看控制台的结果
根据上面的用法 我们可以 看看这种 C 写法
var fromId = document.getElementById.bind(document);
var fromClass = document.getElementsByClassName.bind(document);
var fromTag = document.getElementsByTagName.bind(document);
var fromId_box=fromId('box');
var fromClass_surfaces=fromClass('surfaces');
var fromTag_li=fromTag('li'); console.log('fromId'+fromId_box.innerHTML);
console.log('fromClass'+fromClass_surfaces[0].innerHTML); //
console.log('fromTag'+fromTag_li[0].innerHTML);//
上面 C 写法没啥大问题,C 写法 不推荐;还不如以下的 老老实实的,性能又好;
var doc=document;
var box=doc.getElementById("box");
var li=box.getElementsByTagName("li");
var surfaces=box.getElementsByClassName("surfaces");
另外;我们梳理下基于 querySelectorAll的事件绑定,从 Array.prototype中剽窃了 forEach 方法来完成遍历
Array.prototype.forEach.call(document.querySelectorAll('.surfaces'), function(el){
el.addEventListener('click', someFunction);
}); //通过 bind() 遍历DOM节点的函数。。
var unboundForEach = Array.prototype.forEach,
forEach = Function.prototype.call.bind(unboundForEach); forEach(document.querySelectorAll('.surfaces'), function (el) {
el.addEventListener('click', someFunction);
});
http://www.cnblogs.com/surfaces/
关于bind()的用法, bind()与call(),apply()用法 类似,都是改变当前的this指针。这里简单阐述做个示例;
document.getElementById("box").addEventListener("click",function(){
var self=this; //缓存 this 对象
setTimeout(function(){
self.style.borderColor='red';
},500)
},false); document.getElementById("box").addEventListener("click",function(){
setTimeout(function(){
this.style.borderColor='red';
}.bind(this), 500); //通过bind 传入 this
},false);
另外一种事件绑定方法,不在阐述;
//以下是Andrew Lunny已经想出来的一些东西: https://remysharp.com/2013/04/19/i-know-jquery-now-what#backToTheFutureToday-heading
var $ = document.querySelectorAll.bind(document);
Element.prototype.on = Element.prototype.addEventListener; $('#somelink')[0].on('touchstart', handleTouch);
我们根据这个结合bind 一起使用
//我们将绑定事件在 完善一下
Element.prototype.on = Element.prototype.addEventListener; queryAll('#box')[0].on('click',function(){ //on 类似 jquery
//document.getElementById("box").on("click",function(){
setTimeout(function(){
this.style.borderColor='blue';
console.log('on事件 边框变蓝色');
}.bind(this), 500); //通过bind 传入 this });
关于bind兼容性 扩展;
Function.prototype.bind = Function.prototype.bind || function (target) {
var self = this;
return function (args) {
if (!(args instanceof Array)) {
args = [args];
}
self.apply(target, args);
}
};
bind扩展阅读:一起Polyfill系列:Function.prototype.bind的四个阶段
总结一下:移动端dom操作 ,其实只要 getElementById(id), querySelector 和querySelectorAll 已经能够满足大部分的需求了;
document.querySelectorAll.bind(document);
document.querySelector.bind(document);
缺点:
并不适合那些相对复杂或者表单多的单页;也不适合简单项目的主页;如果多人协作,不利于维护;
上面的始终绑定的document,有时候不一定从document查找;没有content上下文;如document.querySelector("#box").querySelector('.surfaces'); 限定范围在id为box下的class surfaces;
看看 Remy Sharp封装的min.js ;值得学习思考 这种思想;或许你觉得不好,一般般,或者不适合项目啊 之类的;这边不是重点;重点是 你就是想不到可以这样写,重点是 看别人怎样写的,为什么可以这样写,优点是什么;
/*globals Node:true, NodeList:true*/
$ = (function (document, window, $) {
// Node covers all elements, but also the document objects
var node = Node.prototype,
nodeList = NodeList.prototype,
forEach = 'forEach',
trigger = 'trigger',
each = [][forEach],
// note: createElement requires a string in Firefox
dummy = document.createElement('i'); nodeList[forEach] = each; // we have to explicitly add a window.on as it's not included
// in the Node object.
window.on = node.on = function (event, fn) {
this.addEventListener(event, fn, false); // allow for chaining
return this;
}; nodeList.on = function (event, fn) {
this[forEach](function (el) {
el.on(event, fn);
});
return this;
}; // we save a few bytes (but none really in compression)
// by using [trigger] - really it's for consistency in the
// source code.
window[trigger] = node[trigger] = function (type, data) {
// construct an HTML event. This could have
// been a real custom event
var event = document.createEvent('HTMLEvents');
event.initEvent(type, true, true);
event.data = data || {};
event.eventName = type;
event.target = this;
this.dispatchEvent(event);
return this;
}; nodeList[trigger] = function (event) {
this[forEach](function (el) {
el[trigger](event);
});
return this;
}; $ = function (s) {
// querySelectorAll requires a string with a length
// otherwise it throws an exception
var r = document.querySelectorAll(s || '☺'),
length = r.length;
// if we have a single element, just return that.
// if there's no matched elements, return a nodeList to chain from
// else return the NodeList collection from qSA
return length == 1 ? r[0] : r;
}; // $.on and $.trigger allow for pub/sub type global
// custom events.
$.on = node.on.bind(dummy);
$[trigger] = node[trigger].bind(dummy); return $;
})(document, this);
HTML5中类jQuery选择器querySelector的高级使用 document.querySelectorAll.bind(document);的更多相关文章
- HTML5中类jQuery选择器querySelector的使用
简介 HTML5向Web API新引入了document.querySelector以及document.querySelectorAll两个方法用来更方便地从DOM选取元素,功能类似于jQuery的 ...
- HTML5中类jQuery选择器querySelector和querySelectorAll的使用
支持的浏览IE8+,Firefox3.5+,Safari3.1+ Chrome和Opera 10+ 1.querySelector()方法接收一个选择符,返回第一个匹配的第一个元素,如果没有返回nul ...
- 第87天:HTML5中新选择器querySelector的使用
一.HTML5新选择器 1.document.querySelector("selector");selector:根据CSS选择器返回第一个匹配到的元素,如果没有匹配到,则返回n ...
- JQuery选择器转义说明
JQuery选择器 JQuery选择器规则, 借用了css1-3的规则(css选择器规则), 因为css本身也需要一套规则来索引DOM元素, 进而进行样式渲染,例如div.blue 表示目标DOM为 ...
- html5 中高级选择器 querySelector
简介 HTML5向Web API新引入了document.querySelector以及document.querySelectorAll两个方法用来更方便地从DOM选取元素,功能类似于jQuery的 ...
- js高级选择器querySelector和querySelectorAll
querySelector 和 querySelectorAll 方法是 W3C Selectors API规范中定义的.他们的作用是根据 CSS 选择器规范,便捷定位文档中指定元素. 目前几乎主流浏 ...
- 高级选择器querySelector和querySelectorAll
Javascript新提供的querySelector和querySelectorAll方法,是仿照CSS选择器功能编写的 querySelector 功能:该方法返回满足条件的单个元素.按照深度优先 ...
- javascript高级选择器querySelector和querySelectorAll
querySelector 和 querySelectorAll 方法是 W3C Selectors API规范中定义的.他们的作用是根据 CSS 选择器规范,便捷定位文档中指定元素. 目前几乎主流浏 ...
- html5 新选择器 querySelector querySelectorAll
querySelector 返回满足条件的单个元素 使用实例 HTML <div id="main">主体布局</div> JS var main =doc ...
随机推荐
- Linq 导出Excel
var d = db.User; Repeater1.DataSource = d.ToList(); Repeater1.DataBind(); string guid = Guid.NewGuid ...
- CSS之box-sizing的用处简介
前几天才发现有 box-sizing 这么个样式属性.研究了一番感觉非常有意思, 通过指定容器的盒子模型类型,达到不同的展示效果 比如:当一个容器宽度定义为 width:100%; 之后.假设再添加 ...
- php获取前一天,前一个月,前一年的时间
获取前一天的时间: $mytime= date("Y-m-d H:i:s", strtotime("-1 day")); 获取三天前的时间: $mytime= ...
- Sybase Unwired Platform(SUP) 经常使用资源整理(不断更新中)
提示:建议刚開始学习的人看三个东西,详见以下的详细内容.然后再去看论坛,官方技术支持站点等资源. SUP移动开发平台 中文视频讲座 SUP入门讲座(Wang Jun) SUP系列学习笔记 SUP实验 ...
- jenkins集群加入Windows 2012 server作为slave
必须安装.net framework 3.5, 參考: http://technet.microsoft.com/en-us/library/dn482071.aspx 不要在windows 2012 ...
- Android定位功能
不说废话,直接说说实现android定位有关的API吧. 这些API都在android.location包下,一共有三个接口和八个类.它们配合使用即可实现定位功能. 三个接口: GpsStatus.L ...
- Python3.4 邮件(包含附件与中国)
import smtplib import os from email.mime.text import MIMEText from email.mime.multipart import MIMEM ...
- Visual C++学习笔记1:一定要注意ANSI和UNICODE差额
最近的研究VC++.下载VS2013,根据<Visual C++开发实战系列>首先hello我写了一个常规样品,结果显示乱码编辑框.夜已经折腾型转变.然后总结很明显ANSI和UNICODE ...
- Sencha Architect 2 的使用
俗话说的好, 工欲善其事必先利其器, 用Sencha开发的语言, 自己可能不太熟悉, 写出来很麻烦, 于是给大家介绍一个工具. 启动程序第一个界面: 单击第一个Go按钮, 创建一个项目.进入以后, 单 ...
- 【LeetCode】【Python解决问题的方法】Best Time to Buy and Sell Stock II
Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...