jQuery操纵DOM元素属性 attr()和removeAtrr()方法使用详解

  jQuery中操纵元素属性的方法:
  attr(): 读或者写匹配元素的属性值.
  removeAttr(): 从匹配的元素中移除指定的属性.
  

attr()方法 读操作

  attr()读操作. 读取的是匹配元素中第一个元素的指定属性值.
  格式: .attr(attributeName),返回值类型:String.读取不存在的属性会返回undefined.
 
  注意选择器的选择结果可能是一个集合,这里仅仅获取的是集合中第一个元素的该属性值.
  看例子:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("button").click(function () {
alert($("p").attr("title"));//获取属性
// this code can only get the first element's attribute.
});
});
</script>
</head>
<body>
<p title="title1">paragraph 1</p>
<p title="title2">paragraph 2</p>
<br/>
<button>get title</button>
</body>
</html>
  运行结果:弹框显示: title1.
 
  想要分别获取每一个元素的属性,需要使用jQuery的循环结构,比如.each()或.map()方法.
  上面的例子可以改成:
<script type="text/javascript">
$(document).ready(function () {
$("button").click(function () {
//get attribute for every element in selection.
$("p").each(function () {
alert($(this).attr("title"));
});
});
});
</script>

  即可分别获取每个元素的属性.

 

attr()方法 写操作

  attr()写操作. 为匹配元素的一个或多个属性赋值.
  一般格式: .attr(attributeName, value), 即为属性设置value.
  返回值类型:jQuery.也即支持链式方法调用.
 
  执行写操作的时候,如果指定的属性名不存在,将会增加一个该名字的属性,即增加自定义属性,其名为属性名,其值为value值.
 
  写属性是为匹配集合中的每一个元素都进行操作的,见例子:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#button1").click(function(){
$("p").attr("title","Hello World"); });
});
</script>
</head>
<body>
<input type="button" id="button1" value="button1"></input>
<p>This is a paragraph.</p>
<div>This is a div.</div>
<p>This is another paragraph.</p>
<div>This is another div.</div>
</body>
</html>
 
  点击按钮之后所有的p都加上了title="Hello World”的属性.
 
  写操作还有以下两种格式:
  .attr(attributes).attr(attributeName, function).
  下面分别介绍.
 
.attr(attributes):
  这里attributes类型是PlainObject,可以用于一次性设置多个属性.
  什么是PlainObject呢,简单理解就是大括号包围的键值对序列.可以参考问后链接说明.
  键和值之间用冒号(:)分隔,每个键值对之间用逗号(,)分隔.
 
  注意: 设置多个属性值时,属性名的引号是可选的(可以有,也可以没有).但是class属性是个例外,必须加上引号.
 
  例子:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#button1").click(function () {
$("p").attr("title", "Hello World");
});
$("#button2").click(function () {
$("div").attr({"title": "some title for div", "hello": "World"});
});
});
</script>
</head>
<body>
<input type="button" id="button1" value="button1"></input>
<input type="button" id="button2" value="button2"></input>
<p>This is a paragraph.</p>
<div>This is a div.</div>
<p>This is another paragraph.</p>
<div>This is another div.</div>
</body>
</html>

  点击两个按钮之后,元素变为:
  其中<div>的hello是一个新增的自定义属性,其value为World.
 
.attr(attributeName, function(index, oldValue)):
  使用一个function来设置属性值.function的第一个参数是index,第二个参数是该属性之前的值.
  看例子:
<!DOCTYPE html>
<html>
<head>
<style>
div {
color: blue;
}
span {
color: red;
}
b {
font-weight: bolder;
}
</style>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("div")
.attr("id", function (index, oldAttr) {
if (oldAttr) {
return "div-id" + index + oldAttr;
} else {
return "div-id" + index;
} })
.each(function () {
$("span", this).html("(id = '<b>" + this.id + "</b>')");
});
}); </script>
</head>
<body> <div id="someId">Zero-th <span></span></div>
<div>First <span></span></div>
<div>Second <span></span></div> </body>
</html>

  上面的例子,对应的页面结果如下:

 
  当使用一个方法来设定属性值的时候,如果这个set的function没有返回值,或者返回了undefined,当前的值是不会被改变的.
  即操作会被忽略.
  还是上面的例子,attr()其中的function返回undefined:
  如下:
<script type="text/javascript">
$(document).ready(function () {
$("div").attr("id", function (index, oldAttr) {
return undefined;
}).each(function () {
$("span", this).html("(id = '<b>" + this.id + "</b>')");
});
});
</script>
 
  返回的页面效果如下:
  即没有进行任何修改操作,还是保持原来的属性值.
 
 
  注意:jQuery不能修改<input>和<button>的type属性,如果修改会在浏览器报错.
  这是因为IE浏览器中不能修改type属性.
 
 

removeAttr()方法

  移除匹配元素集合中每一个元素的指定属性.
  removeAttr()方法调用的是JavaScript的removeAttribute()方法,但是它能用jQuery对象直接调用,并且它考虑到并处理了各个浏览器上的属性名称可能不统一的问题.
  例子:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("input[type=button]").click(function () {
$("div").removeAttr("title");
});
});
</script>
</head>
<body>
<input type="button" value="ClickMe"></input> <div title="hello">Zero</div>
</body>
</html>
 
  点击按钮后,<div>的title属性会被删除.
 
  注意: 用removeAttr()移除onclick在IE6-8上都不会起作用,为了避免这个问题,应该使用.prop()方法.
  比如:
$element.prop( "onclick", null );
console.log( "onclick property: ", $element[ 0 ].onclick );

 

参考资料

  圣思园张龙老师JavaWeb视频75
  w3school jQuery参考手册 jQuery文档操作: http://www.w3school.com.cn/jquery/jquery_ref_manipulation.asp
  jQuery API:
 
 

jQuery操纵DOM元素属性 attr()和removeAtrr()方法使用详解的更多相关文章

  1. jquery中dom元素的attr和prop方法的理解

    一.背景 在编写使用高版本[ jQuery 1.6 开始新增了一个方法 prop()]的jquery插件进行编写js代码的时候,经常不知道dom元素的attr和prop方法到底有什么区别?各自有什么应 ...

  2. JQuery处理DOM元素-属性操作

    JQuery处理DOM元素-属性操作 //操作元素的属性: $('*').each(function(n){ this.id = this.tagName + n; }) //获取属性值: $('') ...

  3. jQuery对html元素的取值与赋值实例详解

    jQuery对html元素的取值与赋值实例详解 转载  2015-12-18   作者:欢欢   我要评论 这篇文章主要介绍了jQuery对html元素的取值与赋值,较为详细的分析了jQuery针对常 ...

  4. Uploadify 3.2 参数属性、事件、方法函数详解

    一.属性 属性名称 默认值 说明 auto true 设置为true当选择文件后就直接上传了,为false需要点击上传按钮才上传 . buttonClass ” 按钮样式 buttonCursor ‘ ...

  5. (转)Uploadify 3.2 参数属性、事件、方法函数详解

    转自http://blog.sina.com.cn/s/blog_5079086b0101fkmh.html Hallelujah博客 一.属性 属性名称 默认值 说明 auto true 设置为tr ...

  6. Uploadify 3.2 参数属性、事件、方法函数详解以及配置

    一.属性 属性名称 默认值 说明 auto true 设置为true当选择文件后就直接上传了,为false需要点击上传按钮才上传 . buttonClass ” 按钮样式 buttonCursor ‘ ...

  7. web进阶之jQuery操作DOM元素&&MySQL记录操作&&PHP面向对象学习笔记

    hi 保持学习数量和质量 1.jQuery操作DOM元素 ----使用attr()方法控制元素的属性 attr()方法的作用是设置或者返回元素的属性,其中attr(属性名)格式是获取元素属性名的值,a ...

  8. JQUERY选择和操作DOM元素(利用正则表达式的方法匹配字符串中的一部分)

    JQUERY选择和操作DOM元素(利用正则表达式的方法匹配字符串中的一部分) 1.匹配属性的开头 $("[attributeName^='value']"); 2.匹配属性的结尾 ...

  9. JS操作DOM元素属性和方法

    Dom元素基本操作方法API,先记录下,方便以后使用. W3C DOM和JavaScript很容易混淆不清.DOM是面向HTML和XML文档的API,为文档提供了结构化表示,并定义了如何通过脚本来访 ...

随机推荐

  1. 理解javascript中的对话框

    前面的话 通常我们调试程序时,如果需要阻塞效果,则要用到alert().但除了alert()以外,window对象还提供了其他3种对话框.本文将详细介绍window对象中的对话框 定义 系统对话框与在 ...

  2. 解决FragmentTabHost切换标题栏变更问题

    现在都流行FragmentTabHost布局.但是所有的fragment都是共享一个actionbar,但是我们又想给每个fragment定义自定义的标题栏.百度google了好久也没有找到解决方案. ...

  3. 应用程序框架实战三十四:数据传输对象(DTO)介绍及各类型实体比较

    本文将介绍DDD分层架构中广泛使用的数据传输对象Dto,并且与领域实体Entity,查询实体QueryObject,视图实体ViewModel等几种实体进行比较. 领域实体为何不能一统江湖? 当你阅读 ...

  4. EntityFramework 如何进行异步化(关键词:async·await·SaveChangesAsync·ToListAsync)

    应用程序为什么要异步化?关于这个原因就不多说了,至于现有项目中代码异步化改进,可以参考:实际案例:在现有代码中通过async/await实现并行 这篇博文内容针对的是,EntityFramework ...

  5. [OpenCV] Samples 12: laplace

    先模糊再laplace,也可以替换为sobel等. 变换效果后录成视频,挺好玩. #include "opencv2/videoio/videoio.hpp" #include & ...

  6. 1Z0-053 争议题目解析175

    1Z0-053 争议题目解析175 考试科目:1Z0-053 题库版本:V13.02 题库中原题为: 175.You are peer reviewing a fellow DBAs backup p ...

  7. 9.Struts2在Action中获取request-session-application对象

    为避免与Servlet API耦合在一起,方便Action类做单元测试. Struts2对HttpServletRequest.HttpSession.ServletContext进行了封装,构造了三 ...

  8. JSP自定义tag

    前端需要调用后端的配置,想起velocity-tools.然而jsp的话,目前只能想到tag和EL表达式了. Tag相当好写,jsp2.0提供了简化写法: 编写一个java类: public clas ...

  9. jQuery-1.9.1源码分析系列(十六)ajax——ajax处理流程以及核心函数

    先来看一看jQuery的ajax核心处理流程($.ajax) a. ajax( [url,] options )执行流程 第一步,为传递的参数做适配.url可以包含在options中 //传递的参数只 ...

  10. 深入剖析tomcat之一个简单的web服务器

    这个简单的web服务器包含三个类 HttpServer Request Response 在应用程序的入口点,也就是静态main函数中,创建一个HttpServer实例,然后调用其await()方法. ...