JSON数据映射之元素可见控制

1、效果:

2、demo 源码

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>javascript test</title>
    <style media="screen">
      .write{
        opacity: 0;
      }
      .visible {
        opacity: 1;
      }
      button{
        transition: opacity 1s ease;
      }
    </style>
</head>
<body>
    <h3>控制前展示的项目依次:</h3> save、stop、cancel -- delete、submit、view -- update、export
    <h3>控制之后展示项目:</h3>
    <button type="button" class="cpe kpi write">save</button>
    <button type="button" class="cpe kpi write">stop</button>
    <button type="button" class="cpe kpi write">cancel</button> --
    <button type="button" class="enb monitor write">delete</button>
    <button type="button" class="enb monitor write">submit</button>
    <button type="button" class="enb monitor write">view</button> --
    <button type="button" class="operator query write">update</button>
    <button type="button" class="operator query write">export</button>

    <h3>控制设置 - options:<font size="1">修改后点击窗口即生效</font></h3>
    <textarea id="jsontxt" rows="18" cols="40">
    {
      cpe:{
          kpi:{
              write: true
          }
      },
      enb:{
          monitor:{
              write: false
          }
      },
      operator:{
          query:{
              write: true
          }
      }
    }
    </textarea>
</body>
<script type="text/javascript">
  document.addEventListener('click',function(){
    var jsonstr = document.querySelector('#jsontxt').value.trim(),
        json = eval('('+jsonstr+')');
    accessControl(json);
  });
  document.dispatchEvent(new Event('click'));
  /**
  * json数据映射到html
  * @param obj: json数据
  * @param path: 根路径,name属性的映射前缀(属性计算用到,使用者不用管)
  **/
  function accessControl(obj,path){
      var props = {};
      for (var key in obj) {
          var propPath = path;
          if (path) propPath = path + '.' + key;
          else propPath = '.'+key;
          /* 迭代子关系 */
          if(typeof obj[key] === 'object') arguments.callee(obj[key], propPath);
          else props[propPath] = obj[key];
      }
       /* 数据映射到 html */
      for (var key in props) {
          var doms = Array.from(document.querySelectorAll(key));
          if(doms.length==0) continue;
          doms.map(function(dom){setPermission(dom,props[key]);})
      }
      function setPermission(domObj,visibale){/* 可见设置 */
          var isHave = Array.from(domObj.classList).includes('visible');
        if(visibale) {
              if(!isHave) domObj.classList.add('visible');
          }else {
              if(isHave) domObj.classList.remove('visible');
          }
      }
  }
</script>
</html>

 

posted @ 2017-11-29 12:21  【云】风过无痕  阅读(220)  评论(0编辑  收藏  举报