繁体   English   中英

html5数据属性的用例

[英]Use case of html5 data attribute

我在使用data属性时遇到问题。 当我使用data(key, value)添加数据或使用removeData删除数据时,它不会将data属性添加/删除到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');
    });
});

[编辑]小提琴: http//codepen.io/Gasimzada/pen/qGzdf

.data(key, value)将存储与匹配元素关联的任意数据,它不会为所选元素添加或更新data- *属性。

如果您需要设置实际的HTML data- *属性,则需要使用以下命令:

$(this).attr("data-class_value", "new value");

您的用例是正确的,您可以使用HTML5数据属性来存储任何数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM