我想使用 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/