HTML5自定义属性 data

  • 自定义属性: data-*(属性名)
  • 作用: 进行数据的缓存
  • 获取: query方式 对象.data(“自定义属性名称–>data-username”)
  • h5的方式 对象.dataset 返回的是属性的集合
  • 自定义属性的写法: data-name --> 对象.name data-age-id -->对象.ageId 使用驼峰命名法
哈哈哈

//1.获取

  var box = document.querySelector("div");
    //获取
    console.log(box.dataset.ageId);
    console.log(box.dataset['username']);//h5
    console.log($(box).data().username);//jquery

//2.设置

 box.dataset.ageId = "40";
    console.log(box.dataset.ageId);
    $(box).data('password','123456')
    console.log($(box).data("username"));//没有data
    console.log($(box).attr("data-username"));
    console.log($(box).data().username);//jquery

使用自定义属性来操作类

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        ul:first-child {
            list-style: none;
        }

        ul:first-child li {
            width: 100px;
            height: 40px;
            line-height: 40px;
            text-align: center;
            color: #fff;
            background: cyan;
            float: left;
            cursor: pointer;
        }

        ul:first-child li.active {
            background: red;
        }

        .box li{
            width: 400px;
            height: 400px;
            background: pink;
            display: none;
        }
        .box li.show{
            display: block;
        }
    </style>
</head>
<body>
<ul class="nav">
    <!--在渲染的时候  大小的属性会转换成小写 -->
    <li data-content-id="content01">菜单1</li>
    <li data-content-id="content02" class="active">菜单2</li>
    <li data-content-id="content03">菜单3</li>
    <li data-content-id="content04">菜单4</li>
</ul>
<!--怎么关联下面的内容--通过自定义属性也可以进行关联 -->
<ul class="box">
    <li id="content01">内容1</li>
    <li id="content02" class="show">内容2</li>
    <li id="content03">内容3</li>
    <li id="content04">内容4</li>
</ul>
<script src="js/jquery-1.8.3.min.js"></script>
<script>
    $(".nav>li").click(function(){
        document.querySelector("li.active").classList.remove("active");
        this.classList.add('active');
        document.querySelector("li.show").classList.remove("show");
        $("#"+this.dataset.contentId)[0].classList.add('show');
    })
</script>
</body>
</html>

按navigation中每个导航栏,会对应显示对应的内容
效果图如下
HTML5自定义属性 data_第1张图片

你可能感兴趣的:(web)