扩展jquery的选择器
I’m sure you all know that it’s possible to create plugins and extend various aspects of the jQuery JavaScript library but did you know you could also extend the capabilities of it’s selector engine?
Well, you can! For example, you might want to add a new ‘:inline’ selector which will return those elements that are displayed inline. Have a look:
$.extend($.expr[':'],{
|
Using the above code, when you want to select elements that are displayed inline you can simply include it within the selector:
$(':inline'); // Selects ALL inline elements
|
That was a pretty simple example but I’m sure you can see the endless possibilites that this enables! And, creating a custom jQuery selector couldn’t really be simpler!
Loaded images selector
You might want to add a ‘loaded’ selector which will work with images, and will return those images that are loaded:
// Flag images upon load: |
Querying element data
jQuery’s ‘data’ function allows us to add special data to elements without having to pollute global variables or add invalid element attributes. One of the things that jQuery lacks is the capability to easily query elements according to their data. For example, one might decide to flag all elements added dynamically (with jQuery) as ‘dom':
// New element: |
Currently there’s no easy way to select all elements that have been flagged but what if we added a new ‘:data’ selector which could query such information?
Here’s how we would do it:
// Wrap in self-invoking anonymous function: |
Usage
Now, selecting elements which have that ‘dom’ flag is really easy:
$(':data(dom)'); // All elements with 'dom' flag
|
The ‘:data’ extension also allows you to query by comparison, for example:
$(':data(ABC=123)'); // All elements with a data key of 'ABC' equal to 123
|
It also allows you to use regular expressions:
// Let's assume we have slightly varying data across a set of elements: |
Additionally, you can select elements on a basis of whether or not they have ANY data applied to them:
$(':data'); // All elements with data
|
Some other examples:
:red
// Check if color of element is red:
$.extend($.expr[':'],{
red: function(a) {
return $(a).css('color') === 'red';
}
});
// Usage:
$('p:red'); // Select all red paragraphs:childOfDiv
// Check if element is a child of a div:
$.extend($.expr[':'],{
childOfDiv: function(a) {
return $(a).parents('div').size();
}
});
// Yes, I know this is exactly the same as $('div p')
// This is just a demonstration! ;)
// Usage:
$('p:childOfDiv'); // Select all paragraphs that have a DIV as a parent:width()
// Check width of element:
$.extend($.expr[':'],{
width: function(a,i,m) {
if(!m[3]||!(/^(<|>)d+$/).test(m[3])) {return false;}
return m[3].substr(0,1) === '>' ?
$(a).width() > m[3].substr(1) : $(a).width() < m[3].substr(1);
}
});
// Usage:
$('div:width(>200)'); // Select all DIVs that have a width greater than 200px
// Alternative usage:
$('div:width(>200):width(<300)'); // Select all DIVs that have a width greater
// than 200px but less than 300px:biggerThan()
// Check whether element is bigger than another:
$.extend($.expr[':'],{
biggerThan: function(a,i,m) {
if(!m[3]) {return false;}
return $(a).width() * $(a).height() > $(m[3]).width() * $(m[3]).height();
}
});
// Usage:
$('div:biggerThan(div#banner))'); // Select all DIVs that are bigger than #banner
// Alternative usage: (something a little more complex)
// (Making use of custom width() selector)
// Select all DIVs with a width less than 600px but an overall
// size greater than that of the first paragraph which has a
// size greater than img#header:
$('div:width(<600):biggerThan(p:biggerThan(img#header):eq(0))');
Like I said, the possibilities are endless…
UPDATE
I’ve created a couple more examples, take a look:
:external
// Check whether links are external:
// (Only works with elements that have href):
$.extend($.expr[':'],{
external: function(a,i,m) {
if(!a.href) {return false;}
return a.hostname && a.hostname !== window.location.hostname;
}
});
// Usage:
$('a:external'); // Selects all anchors which link to external site/page:inView
// Check whether element is currently within the viewport:
$.extend($.expr[':'],{
inView: function(a) {
var st = (document.documentElement.scrollTop || document.body.scrollTop),
ot = $(a).offset().top,
wh = (window.innerHeight && window.innerHeight < $(window).height()) ? window.innerHeight : $(window).height();
return ot > st && ($(a).height() + ot) < (st + wh);
}
});
// Usage:
$('div:inView'); // Selects all DIV elements within the current viewport
// Alternative Usage:
if ( $('div#footer').is(':inView') ) {
// Do stuff...
}
UPDATE #2
I’ve created a plugin which makes it a little easier to add new ‘:’ selectors. Although, it’s not really a ‘plugin’, it’s just a function which resides under the jQuery namespace:
(function($){
|
Creating a new selector with the ‘newSelector’ plugin:
// Method 1: |
Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!
from http://james.padolsey.com/javascript/extending-jquerys-selector-capabilities/
扩展jquery的选择器的更多相关文章
- jquery选择器扩展之样式选择器
https://github.com/wendux/style-selector-jQuery-plugin http://blog.csdn.net/duwen90/article/details/ ...
- jQuery 各种选择器 $.()用法
jQuery 元素选择器jQuery 使用 CSS 选择器来选取 HTML 元素. $("p") 选取 <p> 元素. $("p.intro") 选 ...
- 扩展jquery easyui datagrid编辑单元格
扩展jquery easyui datagrid编辑单元格 1.随便聊聊 这段时间由于工作上的业务需求,对jquery easyui比较感兴趣,根据比较浅薄的js知识,对jquery easyui中的 ...
- 扩展 -------jQuery
本文摘要:http://www.liaoxuefeng.com/ 编写jQuery插件 为了满足需求,我们经常会调用一些插件,js插件都是别人写的,今天就来了解了解一些方法. 给jQuery对象绑定一 ...
- JQuery 实践--扩展JQuery
Why扩展JQuery通过扩展可以利用JQuery所提供的现有代码基础.避免从头编写代码 有效扩展JQuery的规则扩展JQuery的两种形式: $上直接定义实用工具函数 和JQuery包装集进行操作 ...
- jQuery学习笔记——jQuery常规选择器
一.简单选择器在使用 jQuery 选择器时,我们首先必须使用“$()”函数来包装我们的 CSS 规则.而CSS 规则作为参数传递到 jQuery 对象内部后,再返回包含页面中对应元素的 jQuery ...
- jQuery 的选择器常用的元素查找方法
jQuery 的选择器常用的元素查找方法 基本选择器: $("#myELement") 选择id值等于myElement的元素,id值不能重复在文档中只能有一个id值是myE ...
- HTML 学习笔记 JQuery(选择器)
学习前端也有一段时间了,今天终于进入到JQuery阶段了,对于新手来讲,JQuery的选择器类型之多 功能之强大实在不是一天两天能够记得完的.现在,就采用边学边记录的方式.以后要是忘了的话,也有一个地 ...
- 扩展 jquery miniui 组件实现自动查询数据
主题 之前写过一篇文章分享了公司basecode查找数据后台是怎么实现的(http://www.cnblogs.com/abcwt112/p/6085335.html).今天想分享一下公司前台是怎么扩 ...
随机推荐
- 延时函数出错,volatile一例
莫名其妙的错误.使用Systick做的延时. 初始化是这样的: //SysTick配置 SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8); if ...
- Hibernate之二级缓存
Hibernate之二级缓存 一.简介 Gaving King曾经对别人说,hibern ...
- vs2012 发布网站时,发布目录为空
当我使用Release Any CPU时为空 使用Release X86就正常发布了 奇怪. 之后再切换回 Release Any CPU时正常发布. 在生成时可以尝试设置好生成配置,先生成,再发布.
- Spring IoC容器总结(未完)
在面向对象系统中,对象封装了数据和对数据的处理,对象的依赖关系常常体现在对数据和方法的依赖上.这些依赖关系可以通过把对象的依赖注入交给框架或IOC容器来完成,这种从具体对象手中交出控制的做法是非常有价 ...
- jcmd、jmc介绍
一.jcmd命令使用 概述 在JDK 1.7之后,新增了一个命令行工具jcmd.它是一个多功能工具,可以用来导出堆,查看Java进程,导出线程信息,执行GC等. 使用示例 下面这个命令能够列出当前运行 ...
- (转)WCF开发框架形成之旅---WCF的几种寄宿方式
WCF寄宿方式是一种非常灵活的操作,可以在IIS服务.Windows服务.Winform程序.控制台程序中进行寄宿,从而实现WCF服务的运行,为调用者方便.高效提供服务调用.本文分别对这几种方式进行详 ...
- jenkins中submodule的使用
尝试过各种插件配置都不行. 最后只好通过命令来更新Submodule了. 首先把Git更新到最新,为什么要更新等会儿再说. 项目里的Submodule要配置好,这是基本的. (检查是否配置好的方法: ...
- Google Developing for Android 一 - 相关上下文介绍
前几天在G+上看到Google Developers站点,有一个Android系列的文章,分享到个人微博,周末闲来没事就学写了下,把它们简单的翻译了下,没想到一发不可收拾,六篇文章全部都翻译完了,有些 ...
- QTP参数化
使用QTP可以通过将固定值替换为参数,扩展测试范围,可以提高测试的灵活性. 在QTP中,我们可以对以下部分进行参数化: 1.对象属性参数化 2.对象名称的参数化 3.对象方法的参数的参数化
- CentOS7.2部署OpenStack(一)—环境准备
1.系统环境 # uname -r 3.10.0-327.el7.x86_64 # cat /etc/redhat-release CentOS Linux release 7.2.1511 (Cor ...