zoukankan      html  css  js  c++  java
  • javascript自定义属性的应用

    你知道吗?JavaScript可以为任何HTML元素添加任意的自定义属性,而且你可能无意中已经使用过自定义属性了,那么自定义属性通常有哪些应用呢?

    1、想用“匹配”、对应关系的时候就用索引值

    2、同时控制多组元素

    3、开关切换,多组元素开关的切换

    就总结到这里,下面来看看几个例子吧

    JavaScript自定义属性索引值:

    HTML:

    <input type="button" value="btn1">
    <input type="button" value="btn2">
    <input type="button" value="btn3">

    JavaScript:

    var aInp=document.getElementsByTagName('input');
    
        for (var i = 0; i < aInp.length; i++) {
            aInp[i].index=i;//自定义属性,就是通常用的索引值
            aInp[i].onclick=function(){
                alert(this.index);//弹出当前点击的是第几个按钮,从0开始
            }
        };

    同时控制多组元素:

    HTML:

    <input type="button" value="0">
    <input type="button" value="0">
    <input type="button" value="0">

    JavaScript:

    var aInp=document.getElementsByTagName('input');
        var arr=['A','B','C','D','E','F','G'];
        for (var i = 0; i < aInp.length; i++) {
            aInp[i].num=0;//自定义属性
            aInp[i].onclick=function(){
                this.value=arr[this.num];
                this.num++;
                if (this.num===arr.length) {
                    this.num=0;
                };
            }
        };

    自定义属性组开关:

    CSS:

    .cont{
            width: 400px;
            margin: 30px auto;
            position: relative;
        }
        .cont input{
            height: 100px;
            width: 100px;
            background: #ddd;
            margin-left: 20px;
            font-size: 30px;
            border:1px solid #ccc;
        }
        .cont .active{
            background: #ffc7d2;
            color: #fff;
            border:1px solid #fc6d88;
        }

    HTML:

    <div class="cont">
        <input type="button" value="btn1">
        <input type="button" value="btn2">
        <input type="button" value="btn3">
    </div>

    JavaScript:

    var aInp=document.getElementsByTagName('input');
    
        for (var i = 0; i < aInp.length; i++) {
            aInp[i].Onoff=true;//自定义属性,切换开关
            aInp[i].onclick=function(){
                if (this.Onoff) {
                    this.className='active';
                    this.Onoff=false;
                }
                else{
                    this.className='';
                    this.Onoff=true;
                };
            }
        };
    纵里寻她千百度,蓦然回首,那人却在灯火阑珊处
  • 相关阅读:
    [转]在nodejs使用Redis缓存和查询数据及Session持久化(Express)
    [转]最常用的商务职场英语邮件100个句式
    [转]玩转Angular2(4)--制作左侧自动定位菜单
    [转]Angular开发(十八)-路由的基本认识
    Consul之:服务注册与发现
    Consul之:key/value存储
    服务容错保护断路器Hystrix之六:服务熔断和服务降级
    延时队列:Java中的DelayQueue
    分布式延迟消息队列实现分析与设计
    基于redis的延迟消息队列设计
  • 原文地址:https://www.cnblogs.com/jnslove/p/5296823.html
Copyright © 2011-2022 走看看