Home  >  Article  >  Web Front-end  >  Jquery下attr和removeAttr的使用方法_jquery

Jquery下attr和removeAttr的使用方法_jquery

WBOY
WBOYOriginal
2016-05-16 18:13:131490browse

下面我们来具体看一下attr的用法:
一、attr(name):取得第一个匹配元素的属性值。通过这个方法可以方便地从第一个匹配元素中获取一个属性的值。如果元素没有相应属性,则返回 undefined 。其中name为string.下面我用一个img元素演示一下这种用法:

复制代码 代码如下:

//html文件中 Jquery下attr和removeAttr的使用方法_jquery
//我们可以用attr获得img元素的src属性,具体用法如下:
$(function(){
var imgSrc = $("img").attr('src');
alert(imgSrc); //显示 a.gif
})

二、attr(key,value):为所有匹配的元素设置一个属性值。key为string属性名,value为object属性值,用法演示:
复制代码 代码如下:

//html文件中 Jquery下attr和removeAttr的使用方法_jquery
//使用此方法设置img的src属性
$(function(){
$("img").attr('src', 'a.gif'); //文件中显示 Jquery下attr和removeAttr的使用方法_jquery
})

三、attr(properties):这是一种在所有匹配元素中批量设置很多属性的最佳方式。 注意,如果你要设置对象的class属性,你必须使用'className' 作为属性名。或者你可以直接使用.addClass( class ) 和 .removeClass( class ).
复制代码 代码如下:

//文件中 Jquery下attr和removeAttr的使用方法_jquery
$(function(){
$("img").attr({src:'a.gif', title:'this is a image', className: 'filter'});
})
// 显示为Jquery下attr和removeAttr的使用方法_jquery

四、attr(key, fn):为所有匹配的元素设置一个计算的属性值。不提供值,而是提供一个函数,由这个函数计算的值作为属性值。
复制代码 代码如下:

//文件中 Jquery下attr和removeAttr的使用方法_jquery
$(function(){
$("img").attr('title', function(){ return this.src }); //显示 Jquery下attr和removeAttr的使用方法_jquery
})

以上介绍的是attr的一些用法,下面是removeAttr的用法 remove故明思意就是移除的意思,从每一个匹配的元素中删除一个属性。它的具体用法就是:
复制代码 代码如下:

//文档中 Jquery下attr和removeAttr的使用方法_jquery
$(function(){
$("img").removeAttr('title'); //显示 Jquery下attr和removeAttr的使用方法_jquery
})

以上介绍了attr和removeAttr的基本用法,在实际的工作中还会遇到一些更为复杂的应用,这就需要我们掌握基本用法的同时,多多总结和尝试其他用法。
Statement:
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