Home > Web Front-end > JS Tutorial > body text

jquery 插件学习(二)_jquery

WBOY
Release: 2016-05-16 17:51:06
Original
1138 people have browsed it

创建全局函数只需通过为jquery对象添加属性即可,而创建jquery对象的方法也可以通过为jquery.fn添加属性来实现,实际上jquery.fn对象就是jquery.prototype原型对象的别名,使用别名更方便引用。

demo:

复制代码 代码如下:

jQuery.fn.test = function(){
alert('这是 jquery 对象方法 ');
}

然后,就可以在任何jquery对象中调用该方法了。
复制代码 代码如下:

$(function(){
$('h1').click(function(){
$(this).test();
});
});

由于这里,并没有任何地方匹配dom节点,所以编写全局函数也是可以的(上一节有讲过哦),但是,在使用jquery对象方法时,函数体内的this关键字总是引用当前的jquery对象,因此我们可以对上面的方法进行重写,实现动态提示信息,代码如下:
复制代码 代码如下:

jQuery.fn.test = function(){
alert(this[0].nodeName); //提示当前jquery对象的dom节点名称
}

重点来了,在上面的示例中,可以看到由于jquery选择器返回的是一个数组类型的dom节点集合,this指针就指向当前这个集合,故要显示当前元素的节点名称,就必须在this指针后面指定当前元素的序号。

思考: 如果jquery选择器匹配多个元素,我们该如何准确指定当前元素的对象呢?-----

要解决这个问题,我们不妨在当前jquery对象方法的环境中调用each()方法,通过隐式迭代的方式,让this指针依次饮用每一个匹配的dom元素对象,例如,针对上一个示例做进一步的修改
复制代码 代码如下:

jQuery.fn.test = function(){
this.each(function(){ //遍历匹配的元素,此处的this表示对象集合
alert(this.nodeName); //提示当前jquery对象的dom节点名称(注意这里与上面的变化哦,下标消失了)
});
}

然后,在调用方法时,就不用担心,jquery选择器所匹配的元素有多少了。例如在下面的例子中,当单击不同的元素,会提示当前的节点名称
复制代码 代码如下:

$(function(){
$('body *').click(function(){
$(this).test();
});
});

复制代码 代码如下:

ceshi


dddddddddd

div元素

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!