How to wrap two dynamic HTML elements?

a 夏天 提交于 2019-12-11 15:47:21

问题


I have the below jquery where i have created the dynamic html structure

var data = [{
  "name": "Afghanistan",
  "code": "A"
}, {
  "name": "AndorrA",
  "code": "A"
}, {
  "name": "Bouvet Island",
  "code": "B"
}, {
  "name": "Cook Islands",
  "code": "C"
}];
$.each(data, function(key, val) {
  if (!$("#aZContent ul." + val.code).is("*")) {
    $("<ul />", {
        "class": val.code,
        "html": "<li>" + val.name + "</li>"
      })
      .appendTo("#aZContent ol")
      .before('<b class=' + val.code + '>' + val.code + '</a></b>');
  } else {
    $("b." + val.code).each(function() {
      if (this.textContent === val.code) {
        $(this).next("ul").append("<li>" + val.name + "</li>");
      }
    })
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="aZContent">
  <ol></ol>
</div>

How to wrap the "b" and "ul" element with "li"

<li>
  <b></b>
  <ul>
    <li></li>
  </ul>
</li>

回答1:


Try utilizing $.each(), .appendTo(), .append(); setting ol li , b class to code property of data.

$(function() {
  var data = [{
    "name": "Afghanistan",
    "code": "A"
  }, {
    "name": "Bouvet Island",
    "code": "B"
  }, {
    "name": "Cook Islands",
    "code": "C"
  }];

  $.each(data, function(key, val) {
    if (!$("#aZContent ul." + val.code).is("*")) {
      // append `<li>` to `ol`
      $("<li />", {
          // set `class` to `val.code`
          "class": val.code,
          // set `li` `html` to `b` , `ul` , `li`
          "html": "<b class=" + val.code + ">" +
            val.code + "</a></b>" +
            "<ul><li>" +
            val.name + "</li></ul>"
        })
        .appendTo("#aZContent ol")
    } else {
      $("b." + val.code).each(function() {
        if (this.textContent === val.code) {
          // append `li` to `ul`
          $(this).next("ul").append("<li>" + val.name + "</li>");
        }
      })
    };
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="aZContent">
  <ol></ol>
</div>


来源:https://stackoverflow.com/questions/30578504/how-to-wrap-two-dynamic-html-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!