javascript jQuery 数据属性未设置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23538335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery data attr not setting
提问by ggdx
This appears very simple but I cannot see why it's not working. The selector is correct however the div .faqContent
is simply not being updated with the data-height
attribute.
这看起来很简单,但我不明白为什么它不起作用。选择器是正确的,但是 div.faqContent
根本没有用data-height
属性更新。
$('.faqItem .faqContent').each(function(){
var h = $(this).height();
$(this).data('height',h);
});
I have checked that var h
is correct, it is in colsole.log as correctly holding the height.
我已经检查过这 var h
是正确的,它在 colsole.log 中正确地保持了高度。
EDITIt's absolutely not conflict, and console shows no errors.
编辑这绝对不是冲突,并且控制台没有显示错误。
回答by T.J. Crowder
The data
function confuses a lot of people, it's not just you. :-)
该data
功能使很多人感到困惑,而不仅仅是您。:-)
data
manages jQuery's internal data object for the element, notdata-*
attributes. data
only uses data-*
attributes to set initial values. It never setsdata-*
attributes on elements.
data
管理元素的 jQuery 内部数据对象,而不是data-*
属性。data
只使用data-*
属性来设置初始值。它从不为元素设置data-*
属性。
If you want to actually set a data-*
attribute, use attr
:
如果要实际设置data-*
属性,请使用attr
:
$(this).attr("data-height", h);
But if you just want this information for future use, data
is fine, just don't expect to see it in the DOM inspector, because jQuery doesn't write this information to the DOM.
但是,如果您只是希望这些信息供将来使用,那data
很好,只是不要期望在 DOM 检查器中看到它,因为 jQuery 不会将此信息写入 DOM。
回答by Mohammad Adil
You will not be able to see it in the element inspector but it is thereas jquery set the data attribute internally.
您将无法在元素检查器中看到它,但它在那里,因为 jquery 在内部设置了数据属性。
try console.log($(this).data('height'));
尝试 console.log($(this).data('height'));
回答by Felix
.data()
is only stores the associated new value in memory(or internally). It'll not change the attribute in the DOM hence you cannot see it updated using inspector tools.
.data()
仅在内存(或内部)中存储关联的新值。它不会更改 DOM 中的属性,因此您无法使用检查器工具看到它更新。
To change the attribute, you can use .attr():
要更改属性,您可以使用.attr():
$('.faqItem .faqContent').each(function(){
var h = $(this).height();
$(this).attr('data-height',h);
});
回答by Stephan Wagner
JQuery .data() stores the value on the element itself, it won't add an attribute.
JQuery .data() 将值存储在元素本身上,它不会添加属性。
If you want to add an attribute, use attr:
如果要添加属性,请使用 attr:
$('.faqItem .faqContent').each(function(){
var h = $(this).height();
$(this).attr('data-height', h);
});