我在使用data属性时遇到问题。当我使用data(key, value)
添加数据或使用removeData
删除数据时,它不会将数据属性添加/删除到html标记;我猜它只在内部javascript中,而不是通过标签。
这个问题也引出了另一个问题,因为我对使用数据属性不是很有经验。数据属性的用例是什么?以下代码是对它们的“合法”用法吗?
<!---
This code is supposed to animate between the sections when button is clicked.
But it doesn't animate from second to third but just appends the next section (so, it becomes contacts+photo, instead of just contacts) because the data attribute is not added to the next section on the first click. I will try to create a fiddle and upload it to show a live result.
-->
<div data-ext="inf-slide">
<section data-step="demographics" data-current="1">
<!-- Content here -->
<button data-next="contacts">
</section>
<section data-step="contacts">
<!-- Content here -->
<button data-next="photo">
</section>
<section data-step="photo">
<!-- Content Here -->
<button data-submit="/submit.php"> <!-- Ajax submit -->
</section>
</div>
$(document).ready(function() {
$('[data-ext="inf-slide"]').find('*[data-step]').hide();
$('[data-ext="inf-slide"]').find('*[data-current]').show();
$('[data-ext="inf-slide"]').find('*[data-next]').click(function(e) {
e.preventDefault();
$next = $('[data-step='+$(this).data('next')+']');
$current = $('*[data-current]').removeData('current');
$next.data('current','1');
$next.slideDown('fast');
$current.slideUp('fast');
});
});
答案 0 :(得分:1)
.data(key, value)
将存储与匹配元素关联的任意数据,它不会将data- *属性添加或更新为所选元素。
如果您需要设置实际的HTML data- *属性,则需要使用:
$(this).attr("data-class_value", "new value");
您的用例是正确的,您可以使用HTML5数据属性来存储任何数据。