如何包装两个动态HTML元素?

时间:2015-06-01 16:24:57

标签: javascript jquery dynamic

我有以下jquery,我已经创建了动态html结构

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>

如何用“li”包装“b”和“ul”元素

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

1 个答案:

答案 0 :(得分:0)

尝试使用$.each().appendTo().append();将ol lib class设置为code的{​​{1}}属性。

&#13;
&#13;
data
&#13;
$(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>");
        }
      })
    };
  });
});
&#13;
&#13;
&#13;