# 动态添加tab选项卡及tab页面内容(ajax请求json数据)

作者:mandy


1.实现效果

# 动态添加tab选项卡及tab页面内容(ajax请求json数据)_第1张图片

2.html部分:

  

3.js部分

 $(document).ready(function () {
       
        $.ajax({
            url:"./json/tab_General.json",  //tab数据存储在json中
            type:"get",
            dataType:'json',
            success: function(data){

                     var dataList=data.data[0].subset;
                     var ifrId =  document.getElementById("ifrContentId");
                
                     for (let value of dataList) {

                         var tabName=value.name;
						//循环获取tab名称显示在页面上
                        var title="";
                         $("#tab_Gnenral").append(title);
                         //默认显示第一个tab也内容
                         if(value.text=="tab1") {
                              var content="
"
; $("#ifrContentId").empty().append(content); } //获取所有tab名称 var res = document.getElementsByClassName('subtab'); for(var i=0;i<res.length;i++){ //给每个tab添加click事件,点击每个tab选项卡显示该选项卡的页面内容 res[i].addEventListener('click',function(e){ if($(this)[0].innerText==value.text) { var content = "
"
; $("#ifrContentId").empty().append(content); //empty()方法删除匹配元素的所有子节点,解决页面切换,内容不变的问题 } }, false); } } } }); })

4.json

{
  "data": [
    {
      "name": "tab",
      "subset": [
        {
          "text": "tab1",
          "name": "overview",
          "visible": "true",
          "href": "https://www.infervision.com/zh-cn",
          "selected": "selected",
          "done": "done"
        },
        {
          "text": "tab2",
          "name": "members",
          "visible": "true",
          "href": "https://www.hao123.com/",
          "selected": "",
          "done": ""
        },
        {
          "text": "tab3",
          "name": "payments",
          "visible": "true",
          "href": "https://nodejs.org/en/docs/",
          "selected": "",
          "done": ""
        },
        {
          "text": "tab4",
          "name": "rejection",
          "visible": "true",
          "href": "https://nodejs.org/en/blog/",
          "selected": "",
          "done": ""
        },
        {
          "text": "tab5",
          "name": "diagnosis",
          "visible": "true",
          "href": "https://nodejs.org/en",
          "selected": "",
          "done": ""
        }
      ]
    }
  ]
}

你可能感兴趣的:(前端技术,js)