使用jQuery从unset属性获取空字符串而不是undefined

时间:2011-07-28 11:50:12

标签: jquery attributes

jQuery documentation表示

  

从jQuery 1.6开始,.attr()方法为尚未设置的属性返回undefined

但是,我有一个案例,我想要一个方法来返回undefined,如果我去寻找一个不是定义的属性,但是一个空字符串用于属性被设定为没有价值。

给出以下标记:

<p data-withvalue="hello there!" data-novalue="">

我希望javascript的工作原理如下:

$('p').attr('data-withvalue') => "hello there!"
$('p').attr('data-novalue') => ""
$('p').attr('data-notthere') => undefined

降级jQuery不是一种选择。这可能吗?

(注意:在Chrome开发者工具中查看“检查元素”,我注意到data-novalue=""已更改为data-novalue。我不知道所有浏览器是否都这样解释,但是我需要这个是跨浏览器兼容的......)

1 个答案:

答案 0 :(得分:0)

除非我弄错了,这正是它与jQuery 1.6.2的合作方式

演示:http://jsfiddle.net/xJfpX/

输出:

hello there!

undefined
相关问题