jquery基于JSON数据填充ul和li

时间:2017-02-03 19:35:15

标签: javascript jquery html json

下面的代码创建了5个ul并填充了所有.dropdown菜单中的li。 如何使用JSON数据(或者可能有更好的方法)让jquery填充正确的ul?

预期产量: 并非所有幻灯片都进​​入所有模块..只有某些幻灯片应该进入特定模块,如JSON数据所示。

var menulist = {"List" : [
{"menutitle" : "Module 1", "mod" : "1"},
{"menutitle" : "Module 2", "mod" : "2"},
{"menutitle" : "Module 3", "mod" : "3"},
{"menutitle" : "Module 4", "mod" : "4"},
{"menutitle" : "Module 5", "mod" : "5"}
]}

var slidelist = {"List" : [
{"slidetitle" : "Slide 1", "mod" : "1"},
{"slidetitle" : "Slide 2", "mod" : "1"},
{"slidetitle" : "Slide 3", "mod" : "1"},
{"slidetitle" : "Slide 4", "mod" : "1"},
{"slidetitle" : "Slide 5", "mod" : "2"},
{"slidetitle" : "Slide 6", "mod" : "2"},
{"slidetitle" : "Slide 7", "mod" : "3"},
{"slidetitle" : "Slide 8", "mod" : "3"},
{"slidetitle" : "Slide 9", "mod" : "3"},
{"slidetitle" : "Slide 10", "mod" : "4"},
{"slidetitle" : "Slide 11", "mod" : "4"},
{"slidetitle" : "Slide 12", "mod" : "5"},
{"slidetitle" : "Slide 13", "mod" : "5"},
{"slidetitle" : "Slide 14", "mod" : "5"},
{"slidetitle" : "Slide 15", "mod" : "5"}
]}


$(document).ready(function(){
    var listmenus = "";
    for (var t = 0; t < menulist.List.length; t++){
        listmenus += "<a href='#' class='dropdown-toggle' data-toggle='dropdown'>" + menulist.List[t].menutitle + "<span class='caret'></span></a><ul class='dropdown-menu'></ul>"
    }
    $(".test").html(listmenus);
});
$(document).ready(function(){
    var listslides = "";
    for (var s = 0; s < slidelist.List.length; s++){
        listslides += "<li><a href='#' class='link'>" + slidelist.List[s].slidetitle + "</a></li>"
    }
   $(".dropdown-menu").html(listslides);
});

4 个答案:

答案 0 :(得分:1)

添加模块var menulist = {"List" : [{"menutitle" : "Module 1", "mod" : "1"},{"menutitle" : "Module 2", "mod" : "2"},{"menutitle" : "Module 3", "mod" : "3"},{"menutitle" : "Module 4", "mod" : "4"},{"menutitle" : "Module 5", "mod" : "5"}]} var slidelist = {"List" : [{"slidetitle" : "Slide 1", "mod" : "1"},{"slidetitle" : "Slide 2", "mod" : "1"},{"slidetitle" : "Slide 3", "mod" : "1"},{"slidetitle" : "Slide 4", "mod" : "1"},{"slidetitle" : "Slide 5", "mod" : "2"},{"slidetitle" : "Slide 6", "mod" : "2"},{"slidetitle" : "Slide 7", "mod" : "3"},{"slidetitle" : "Slide 8", "mod" : "3"},{"slidetitle" : "Slide 9", "mod" : "3"},{"slidetitle" : "Slide 10", "mod" : "4"},{"slidetitle" : "Slide 11", "mod" : "4"},{"slidetitle" : "Slide 12", "mod" : "5"},{"slidetitle" : "Slide 13", "mod" : "5"},{"slidetitle" : "Slide 14", "mod" : "5"},{"slidetitle" : "Slide 15", "mod" : "5"}]} $(document).ready(function(){ var listmenus = ""; for (var t = 0; t < menulist.List.length; t++){ listmenus += "<a href='#' class='dropdown-toggle' data-toggle='dropdown'>" + menulist.List[t].menutitle + "<span class='caret'></span></a><ul data-value=\""+menulist.List[t].mod+"\" class='dropdown-menu'></ul>" } $(".test").html(listmenus); for (var s = 0; s < slidelist.List.length; s++){ $(".dropdown-menu[data-value=" + slidelist.List[s].mod + "]").append("<li><a href='#' class='link'>" + slidelist.List[s].slidetitle + "</a></li>"); } });作为DOM对象的属性将允许您稍后选择它以区分哪些幻灯片放在哪里。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test"></div>
listbox2.get(0,END)

答案 1 :(得分:0)

使用data-*属性保存每个ul的mod值,然后根据该值获取ul。您可以使用对象来保存生成的HTML字符串。

&#13;
&#13;
var menulist = {
  "List": [{
    "menutitle": "Module 1",
    "mod": "1"
  }, {
    "menutitle": "Module 2",
    "mod": "2"
  }, {
    "menutitle": "Module 3",
    "mod": "3"
  }, {
    "menutitle": "Module 4",
    "mod": "4"
  }, {
    "menutitle": "Module 5",
    "mod": "5"
  }]
}

var slidelist = {
  "List": [{
    "slidetitle": "Slide 1",
    "mod": "1"
  }, {
    "slidetitle": "Slide 2",
    "mod": "1"
  }, {
    "slidetitle": "Slide 3",
    "mod": "1"
  }, {
    "slidetitle": "Slide 4",
    "mod": "1"
  }, {
    "slidetitle": "Slide 5",
    "mod": "2"
  }, {
    "slidetitle": "Slide 6",
    "mod": "2"
  }, {
    "slidetitle": "Slide 7",
    "mod": "3"
  }, {
    "slidetitle": "Slide 8",
    "mod": "3"
  }, {
    "slidetitle": "Slide 9",
    "mod": "3"
  }, {
    "slidetitle": "Slide 10",
    "mod": "4"
  }, {
    "slidetitle": "Slide 11",
    "mod": "4"
  }, {
    "slidetitle": "Slide 12",
    "mod": "5"
  }, {
    "slidetitle": "Slide 13",
    "mod": "5"
  }, {
    "slidetitle": "Slide 14",
    "mod": "5"
  }, {
    "slidetitle": "Slide 15",
    "mod": "5"
  }]
}


$(document).ready(function() {
  var listmenus = "";
  for (var t = 0; t < menulist.List.length; t++) {
    listmenus += "<a href='#' class='dropdown-toggle' data-toggle='dropdown'>" + menulist.List[t].menutitle + "<span class='caret'></span></a><ul data-mod='" + menulist.List[t].mod + "' class='dropdown-menu'></ul>"
  }
  $(".test").html(listmenus);

  var listslides = {};
  for (var s = 0; s < slidelist.List.length; s++) {
    listslides[slidelist.List[s].mod] = listslides[slidelist.List[s].mod] || '';
    listslides[slidelist.List[s].mod] += "<li><a href='#' class=;'link'>" + slidelist.List[s].slidetitle + "</a></li>"
  }

  Object.keys(listslides).forEach(function(l) {
    $('.dropdown-menu[data-mod="' + l + '"]').html($('<ul/>', {
      id: l,
      html: listslides[l]
    }))
  })
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test"></div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

我的提案基于Creating New Elements directly in jQuery,例如:

var dp = $('<div/>', {class: 'dropdown'})
      .append($('<button/>', {
          class: 'btn btn-default dropdown-toggle',
          type: 'button',
          id: 'dropdownMenu' + index,
          'data-toggle': 'dropdown',
          'aria-haspopup': true,
          'aria-expanded': true
      }).append(ele.menutitle).append($('<span/>', {class: 'caret'})))
      .append($('<ul/>', {
          class: 'dropdown-menu',
          'aria-labelledby': 'dropdownMenu' + index
      }));

摘录:

&#13;
&#13;
var menulist = {
  "List": [
    {"menutitle": "Module 1", "mod": "1"},
    {"menutitle": "Module 2", "mod": "2"},
    {"menutitle": "Module 3", "mod": "3"},
    {"menutitle": "Module 4", "mod": "4"},
    {"menutitle": "Module 5", "mod": "5"}
  ]
}

var slidelist = {
  "List": [
    {"slidetitle": "Slide 1", "mod": "1"},
    {"slidetitle": "Slide 2", "mod": "1"},
    {"slidetitle": "Slide 3", "mod": "1"},
    {"slidetitle": "Slide 4", "mod": "1"},
    {"slidetitle": "Slide 5", "mod": "2"},
    {"slidetitle": "Slide 6", "mod": "2"},
    {"slidetitle": "Slide 7", "mod": "3"},
    {"slidetitle": "Slide 8", "mod": "3"},
    {"slidetitle": "Slide 9", "mod": "3"},
    {"slidetitle": "Slide 10", "mod": "4"},
    {"slidetitle": "Slide 11", "mod": "4"},
    {"slidetitle": "Slide 12", "mod": "5"},
    {"slidetitle": "Slide 13", "mod": "5"},
    {"slidetitle": "Slide 14", "mod": "5"},
    {"slidetitle": "Slide 15", "mod": "5"}
  ]
}


menulist.List.forEach(function (ele, index) {
  //
  // Create the main dropdown element
  //
  var dp = $('<div/>', {class: 'dropdown'})
  .append($('<button/>', {
    class: 'btn btn-default dropdown-toggle',
    type: 'button',
    id: 'dropdownMenu' + index,
    'data-toggle': 'dropdown'
  }).append(ele.menutitle + ' ').append($('<span/>', {class: 'caret'})))
  .append($('<ul/>', {
    class: 'dropdown-menu',
    'aria-labelledby': 'dropdownMenu' + index
  }));
  var cachedInsertPoint = dp.find('ul');
  slidelist.List.filter( (e, i) => { return e.mod == ele.mod }).forEach(function(e, idx) {
    //
    // for each corresponding element in the second array
    // add the relative option
    //
    cachedInsertPoint.append($('<li/>').append($('<a/>', {
      href: '#',
      text: e.slidetitle
    })));
  });
  $('body').append(dp);
});
&#13;
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您似乎想要做的事情非常简单。我想你正试图将子列表分成适当的父母。只需在与父循环相同的范围内运行循环。然后你知道属于哪里!

以下是使用更多jQuery“权限”的方法,例如 $.each $.('<element />') { {3}}

  

仅供参考,没有所有评论和拆分项目,后面的代码可以简单如下:甚至可以整理甚至更少!

$(function() {
    $.each(listMenu.List, function(ind, arr) {
        var a = $('<a />', { 'data-toggle': 'dropdown', href: 'javascript:void(0)' }).addClass('dropdown-toggle').text(arr.menutitle),
            span = $('<span />').addClass('caret').appendTo(a),
            ul = $('<ul />');
        $.each(listSlide.List, function(slideInd, slideArr) {
            if (slideArr.mod == arr.mod) {
                var li = $('<li />').appendTo(ul);
                $('<a />', { href: 'javascript:void(0)' }).addClass('link').text(slideArr.slidetitle).appendTo(li);
            }
        });
        $('.test').append(a, ul);
    });
});

Explination示例

var listMenu = JSON.parse('{"List":[{"menutitle":"Module 1","mod":"1"},{"menutitle":"Module 2","mod":"2"},{"menutitle":"Module 3","mod":"3"},{"menutitle":"Module 4","mod":"4"},{"menutitle":"Module 5","mod":"5"}]}'),
	listSlide = JSON.parse('{"List":[{"slidetitle":"Slide 1","mod":"1"},{"slidetitle":"Slide 2","mod":"1"},{"slidetitle":"Slide 3","mod":"1"},{"slidetitle":"Slide 4","mod":"1"},{"slidetitle":"Slide 5","mod":"2"},{"slidetitle":"Slide 6","mod":"2"},{"slidetitle":"Slide 7","mod":"3"},{"slidetitle":"Slide 8","mod":"3"},{"slidetitle":"Slide 9","mod":"3"},{"slidetitle":"Slide 10","mod":"4"},{"slidetitle":"Slide 11","mod":"4"},{"slidetitle":"Slide 12","mod":"5"},{"slidetitle":"Slide 13","mod":"5"},{"slidetitle":"Slide 14","mod":"5"},{"slidetitle":"Slide 15","mod":"5"}]}');

//  this shorthand expression is same as `$(document).ready(function(){`, FYI, you don't have to write this over and over, once is enough.
$(function() {
	//  filter through the parent list that will make each list
	$.each(listMenu.List, function(ind, arr) {
		//  basics to making an element object in jQuery:
		//  `$("<tagName />", { attributes: value })`
		var a = $('<a />', { 'data-toggle': 'dropdown', href: 'javascript:void(0)' }).text(arr.menutitle),	//  create head link element	//  use of javascript:void(0) tends to be prefered over # unles u have specific purpose for such
			span = $('<span />').appendTo(a),	//  create caret span & insert into our a tag
			ul = $('<ul />') //  create ul element
		
		//  add Classes // only did this here for simplicity of view
		//  Just FYI, this can be done in one line when establish variable above.
		//  Return is always the jQuery Element Object
		a.addClass('dropdown-toggle');
		span.addClass('caret');
		
		//  no need for an extra loop after this one, lets just loop through our sub list here
		//  quick and easy and you can associate better what belongs where without use of extra ID's and such
		$.each(listSlide.List, function(slideInd, slideArr) {
			if (slideArr.mod == arr.mod) {	//  check if item belongs in this list
				var li = $('<li />').appendTo(ul),	//  create li element & insert into our list
					liA = $('<a />', { href: 'javascript:void(0)' }).addClass('link').text(slideArr.slidetitle).appendTo(li);	//  create and append
			}
		});
		
		$('.test').append(a, ul);
	});
	
	// Just for a little fun and further education, let's add some functionality!
	//  Here, I'll assign "events" to slide the list up and down,
	//  but the elements are added "dynamically", so I'll instead assign the events to
	//  a "static parent" (in this case the DOM) and associate what elements
	//  the event belongs to with my 2nd parameter.
	//  Read more about this here: http://api.jquery.com/on/
	$(document)
		.on('click', '.dropdown-toggle', function(e) {
			//  this is the HTML element,
			//  wrapping it in $() gives us jQuery object methods!
			//  Read about the .next method here: http://api.jquery.com/next/
			//  I use $.stop to stop and complete any animation in progress (multiclicking issues)
			//  Read about .stop here: http://api.jquery.com/stop/
			//  I use slideToggle to make the menu go up and down!
			//  Read about .slideToggle here: http://api.jquery.com/slideToggle/
			$(this).next('ul').stop(true, true).slideToggle();
		})  //  finally, notice i did not close this `);`
			//  This is because I wanted to show you, you can use jQuery "chaining"
			//  to continue. So, if you wanted to add more events for other elements,
			//  you would just put a `.on(` and keep going, like so:
			//
			//    $(document)
			//      .on('event', 'selector', function(e) {})
			//      .on('event', 'selector', function(e) {})
			//      .on('event', 'selector', function(e) {})
			//      .on('event', 'selector', function(e) {})
			//      .on('event', 'selector', function(e) {})
});
.test > a { display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="test"></div>