HTML5自定义属性 data

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

//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中每个导航栏,会对应显示对应的内容
效果图如下
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值