您的浏览器过于古老 & 陈旧。为了更好的访问体验, 请 升级你的浏览器
Ready 发布于2014年08月22日 04:16

原创 jQuery.removeAttr() 函数详解

3176 次浏览 读完需要≈ 6 分钟

内容目录

removeAttr()函数用于移除在当前jQuery对象所匹配的每一个元素节点上指定的属性

该函数属于jQuery对象(实例)。如果你需要设置或获取元素节点上的某些属性值,你可以使用attr()函数。

语法

removeAttr()函数的语法如下:

jQueryObject.removeAttr( attributeNames )

注意removeAttr()会移除当前jQuery对象所匹配的每一个元素上指定名称的属性。

参数

参数 描述
attributeNames String类型指定的属性名称。

jQuery 1.7 新增支持:你可以传入以空格分隔的字符串,空格隔开的每个子字符串即是需要移除的属性名称。

返回值

removeAttr()函数的返回值是jQuery类型,返回当前jQuery对象本身。

在IE 6 ~ IE 8中,removeAttr()函数无法移除行内的onclick事件属性,为了避免潜在的问题,请使用prop()函数,相关代码如下:jQueryObject.prop("onclick", null);

示例&说明

以下面这段HTML代码为例:

<div id="n1">
    <img id="n2" data-id="12" alt="站点名称" title="CodePlayer" src="/image/blank.gif" >
    <img id="n3" data-id="15" alt="站点logo" title="专注于编程开发技术分享" src="http://localhost/static/image/site-url.png" >
</div>

我们编写如下jQuery代码:

var $imgs = $("img");
// 移除所有img元素的data-id属性
$imgs.removeAttr("data-id");

var $n2 = $("#n2");
var $n3 = $("#n3");
document.writeln( $n2.attr("data-id") ); // undefined
document.writeln( $n3.attr("data-id") ); // undefined

// 从jQuery 1.7开始,可以同时移除alt和title属性
// 在jQuery 1.6之前的某些版本中,属性名称包含空格会抛出错误"Uncaught InvalidCharacterError: The string contains invalid characters. "
// 在jQuery 1.6.x中,属性名称包含空格,不会抛出错误,而是忽略掉本次移除操作
$imgs.removeAttr("alt title");
document.writeln( $n2.attr("alt") ); // undefined (站点名称){小括号内表示在jQuery 1.6.x中的输出内容,下同} 
document.writeln( $n2.attr("title") ); // undefined (CodePlayer)
document.writeln( $n3.attr("alt") ); // undefined (站点logo)
document.writeln( $n3.attr("title") ); // undefined (专注于编程开发技术分享)

运行代码

  • CodePlayer技术交流群1
  • CodePlayer技术交流群2

0 条评论

撰写评论

打开导航菜单