jquery hasAttr in Webkit and Opera
Aloha,
I found an answer to my question here. Basically i'm looking to tell if a tag has an attribute. I don't care what the value is, just if there is one.
I'm currently using:
$.fn.hasAttr = function (attr) {
var attribVal = this.attr(attr);
alert(attr+" ["+attribVal+"]");
return (attribVal !== undefined) && (attribVal !== false);
};
This function is not working in Opera or Webkit. It returns true even if the attribute does not exist. The alert that I added shows that the attribVal
is equal to blank, not false, not undefined, not null, but blank. Firefox and IE this works fine in as attribVal
is undefined.
The problem is I want it to return true for a blank attribute, if its on the tag and false for no attribute on the tag.
Edit: expected results...
<tag /> should be hasAttr('placeholder') = false
<tag placeholder /> should be hasAttr('placeholder') = true
<tag placeholder="" /> should be hasAttr('placeholder') = true
<tag placeholder="Hi" /> should be hasAttr('placeholder') = true
Edit: Current code
This works in WebKit and FF, not in IE or Opera.
Update After all this, my original code works, unless I am looking at the placeholder attribute. Opera and webkit return true for all four options when I'm looking at the placeholder attribute. See here for an example. I've updated my expected results to use the placeholder attribute.
这应该适用于所有浏览器:
$.fn.hasAttr = function (attr) {
for (var i = 0; i < this[0].attributes.length; i++) {
if (this[0].attributes[i].nodeName == attr) {return true}
}
return false;
};
A simple, jQuery-ish solution would be:
$.fn.hasAttr = function(attr) {
return this.is('[' + attr + ']');
};
jsFiddle. NB I haven't got access to IE or Opera right now to test this...
You shouldn't check explicitly against undefined
, but just check for falsy values
.
return !!attribVal;
That will return false
for null
, undefined
, ""
, NaN
, 0
and of course false
.
Read more about !!
.
Update
Your desired behavior should be possible invoking Sizzle:
$.fn.hasAttr = function (attr) {
var attribVal = this.attr(attr);
return (typeof attribVal === 'string');
};
Example : http://jsfiddle.net/4UJJk/11/
链接地址: http://www.djcxy.com/p/13010.html