admin管理员组文章数量:1429735
I'm using the html5 "data" attribute on a element, and I want to assign the attribute value to a variable only if it exists and if it's not empty:
var xxx = $(this).data('what') ? $(this).data('what') : 'default_value';
but it doesn't work. I always get the default value...
I'm using the html5 "data" attribute on a element, and I want to assign the attribute value to a variable only if it exists and if it's not empty:
var xxx = $(this).data('what') ? $(this).data('what') : 'default_value';
but it doesn't work. I always get the default value...
Share Improve this question edited Nov 17, 2015 at 21:51 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Apr 28, 2011 at 16:10 AlexAlex 66.2k185 gold badges460 silver badges651 bronze badges 3- 1 are you sure that data-what exists at any point? – Naftali Commented Apr 28, 2011 at 16:12
- 1 Have you outputted the conditional part of the statement to see whether it can actually resolve to true and false? If not, change your conditional so it works. – James Commented Apr 28, 2011 at 16:13
-
ok, the problem was
$(this)
was something else than what I was expecting :) sorry for being dumb :x – Alex Commented Apr 28, 2011 at 16:38
3 Answers
Reset to default 5Using a short circuit is simpler and more efficient:
var xxx = $(this).data('what') || 'default_value';
But your code should have worked anyway, assuming the data existed (as the menter noted).
Looks like $(this) is not what you expect it to be. Other than that, the statement looks fine. Demo
According to the documentation:
.data()
The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.
.attr()
The .attr() method gets the attribute value for only the first element in the matched set.
So what you want is to use the .attr() method, like this:
var xxx = $(this).attr('data-what') || 'default_value';
本文标签: javascriptjQuery data() conditional statementStack Overflow
版权声明:本文标题:javascript - jQuery $.data() conditional statement - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745474542a2659901.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论