jquery - 如果我调用 .attr(attributeName, null) 会发生什么?属性被删除了吗?

标签 jquery

我想使用 jQuery 有条件地添加属性:

var $this = this
.append(...)
...

if (someCondition)
    this.attr(...)

return $this;

那个愚蠢的条件属性添加破坏了我的 jQuery 方法调用链的美感。但是,如果 .attr(someAttr, null) 删除了属性 someAttr:

return this
.append(...)
....
.attr(someAttr, someCondition ? someValue : null);

所以问题是:.attr(someAttr, null)是否删除属性someAttr

最佳答案

要使用 jquery 删除属性,请使用 .removeAttr .

根据this answer ,从 1.3 开始,至少使用 null 实际上会导致重载函数仅调用 .attr(attributeName),返回当前值。

要设置空值,请使用 .attr(attributeName, '')

要有条件添加属性,请使用

var val = $("#selector").attr(attributeName); // the current value, undefined if not set
$("#selector").attr(attributeName, val ? val : valToSet);  
// if the value is set, use it, otherwise pass the default in

关于jquery - 如果我调用 .attr(attributeName, null) 会发生什么?属性被删除了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5142719/

相关文章:

javascript - 我如何将其转换为数组?

javascript - jquery同位素未捕获错误

jQuery 公式解析器?

javascript - jQuery/jQuery 移动点击/滑动事件

javascript - 使用 AJAX 更新从数据库(mysql)检索的数据

javascript - 如何将css字符串转换为数组

jquery - 防止 JQuery Mobile 可折叠集 header 被截断

c# - webapi 不会使用 $.param 反序列化字符串数组

javascript - 如何使用jquery获取UL的if子属性?

jquery - CSS/JQuery 选择器奇怪的行为