这看起来很简单,但我不明白为什么它不起作用。选择器是正确的,但是 div .faqContent
根本没有使用 data-height
属性进行更新。
$('.faqItem .faqContent').each(function(){
var h = $(this).height();
$(this).data('height',h);
});
我已检查 var h
是否正确,它在 colsole.log 中正确保持高度。
编辑 绝对不冲突,控制台也没有显示错误。
最佳答案
data
函数让很多人感到困惑,不仅仅是你。 :-)
data
管理元素的 jQuery 内部数据对象,而不是 data-*
属性。 data
仅使用 data-*
属性来设置初始值,而且,它会根据它们的内容猜测您希望它们是什么类型看起来像(因此看起来像数字的东西会转换为数字;看起来像 JSON 的东西会转换为对象)。 data
方法从不设置元素上的data-*
属性,它仅在其内部数据对象上设置数据。这意味着两者(内部数据对象和属性)不同步:
const t = $("#target");
let value;
// Getting the attribute always gets a string
value = t.attr("data-height");
console.log(`${value} (${typeof value})`); // 1 (string)
// Using `.data`, jQuery will guess that because the attribute looks like a number,
// you want it converted to a number
value = t.data("height");
console.log(`${value} (${typeof value})`); // 1 (number)
// `data` only sets the internal data object properties, not the attribute...
t.data("height", 2);
// ...so the attribute still has `"1"`
value = t.attr("data-height");
console.log(`${value} (${typeof value})`); // 1 (string)
// ...even though the data object has 2
value = t.data("height");
console.log(`${value} (${typeof value})`); // 2 (number)
<div id="target" data-height="1"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
如果您想实际设置 data-*
属性,请使用 attr
:
$(this).attr("data-height", h);
const t = $("#target");
let value;
value = t.attr("data-height");
console.log(`${value} (${typeof value})`); // 1 (string)
// `attr` converts whatever you give it to string
t.attr("data-height", 2);
value = t.attr("data-height");
console.log(`${value} (${typeof value})`); // 2 (string)
<div id="target" data-height="1"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
但是,如果您只想将此信息供将来使用,那么 data
就可以(假设您可以接受它的自动类型转换),只是不要指望在 DOM 检查器中看到它,因为 jQuery 不会将此信息写入 DOM。
关于javascript - jQuery 数据属性未设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23538335/