开发者

What happens if I call .attr(attributeName, null)? Is the attribute removed?

I want to conditionally add an attribute using jQuery:

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

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

return $this;

That single silly conditional attribute addition breaks the beauty of my chain of jQuery method invocations. However, this could be overcome if .attr(someAttr, null) deleted the attibute someAttr:

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

So the question is: Does .attr(someAttr, null) delete the attri开发者_如何学运维bute someAttr?


To remove an attribute using jquery, use .removeAttr.

According to this answer, as of 1.3 at least using null would actually cause the overloaded function to call just .attr(attributeName), returning the current value.

To set an empty value, use .attr(attributeName, '')

For conditional adding of an attribute, use

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


It doesn't delete the attribute, but it should work to clear its value. Though to be sure you may want to set it to an empty string instead.

.attr(someAttr, someCondition ? someValue : '');

Or you could pass it a function that runs the condition:

.attr(someAttr, function(i,attr){  return someCondition ? someValue : ''; });


I don't know, but if you are trying to remove an attribute, why not just use removeAttr?

http://api.jquery.com/removeAttr/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜