The jQuery documentation states that
As of jQuery 1.6, the
.attr()
method returnsundefined
for attributes that have not been set.
However, I have a case where I'd like a method to return undefined
if I go looking for an attribute that is not defined, but an empty string for attributes that have been set to have no value.
Given the following markup:
<p data-withvalue="hello there!" data-novalue="">
I'd like javascript that works like this:
$('p').attr('data-withvalue') => "hello there!"
$('p').attr('data-noval开发者_开发问答ue') => ""
$('p').attr('data-notthere') => undefined
Downgrading jQuery is not an option. Is this possible?
(Note: looking at "inspect element" in the Chrome developer tools, I note that data-novalue=""
has been changed to data-novalue
. I don't know if all browsers interpret it like that, but I need this to be cross-browser compatible...)
Unless I'm mistaken, that's exactly how it's working with jQuery 1.6.2
Demo: http://jsfiddle.net/xJfpX/
Output:
hello there!
undefined
精彩评论