0

我有一个 ajax 调用,它根据返回的内容创建一个列表:

$.ajax({
    type: "POST",
    url: "Home/FillTags",
    data: "{ 'mydataishere' }",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
     $('.placetags').html('');
     $('.placetags').append("<div class=\"tags\">");
        var i = 0;           
        $.each(msg, function () {
            $('.placetags').append("<li><a href='javascript:void(0)' onclick=\"fnKeyWordSearch({'type' : '2' , 'tag' : '" + msg[i].TagID + "'});\"> " + msg[i].Tag + "</a></li>");
            i++;
        });
     $('.placetags').append("</div>");
    }
});

ajax 正在返回正确的列表,这是我希望看到的呈现 HTML:

<div class="placetags">
  <div class="tags">
    <li>...</li>
    <li>...</li>
    <li>...</li>
  </div>
</div>

但是......这就是我得到的......

<div class="placetags">
  <div class="tags"></div>
    <li>...</li>
    <li>...</li>
    <li>...</li>    
</div>

我不明白为什么div 在's 被放入.tags之前被关闭。<li>我的 css 是写<li>在里面的.tags ,我不明白为什么会这样。

4

3 回答 3

1

只是不正​​确的嵌套,试试这个:

$('.placetags').append("<div class=\"tags\">");
    var i = 0;           
    $.each(msg, function () {
        $('.tags').append("<li><a href='javascript:void(0)' onclick=\"fnKeyWordSearch({'type' : '2' , 'tag' : '" + msg[i].TagID + "'});\"> " + msg[i].Tag + "</a></li>");
        i++;
    });
于 2012-12-05T19:05:17.360 回答
0

您需要将它附加到您刚刚创建的 div 中。而不是容器 div

$('.placetags').append("<div class=\"tags\" />"); // <-- make sure you close or it breaks in IE
        var i = 0;           
        $.each(msg, function () {
            $('.placetags div.tags').append("<li><a href='javascript:void(0)' onclick=\"fnKeyWordSearch({'type' : '2' , 'tag' : '" + msg[i].TagID + "'});\"> " + msg[i].Tag + "</a></li>");
            i++;
        });
于 2012-12-05T19:02:21.867 回答
0

This is because each(!) call to .append() will add a complete HTML element, including its content and its closing tag!

If you want to avoid this, you'd have to create the full HTML to be appended first, and only use .append() when the HTML is complete.

于 2012-12-05T18:59:13.963 回答