Javascript/jQuery执行顺序问题 [英] Javascript/jQuery execution order question

查看:76
本文介绍了Javascript/jQuery执行顺序问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery尝试通过JSON对象(使用async getJson调用)从JSON对象构造用于Web应用程序的表,而我难以深入到执行顺序的底部.

I am using jQuery to try and construct a table for a web app from a JSON object (using the async getJson call), and I am having difficulty getting to the bottom of the order of execution.

我的JS是:

//create table header
$('#peopleDirectory').append(
    "<table><thead><tr><th>column header!</th>"
    +"</tr></thead><tbody>"
);

//iterate through list to create table row:
$.each(jsonArray.members, function(i, membObj) {
    $('#peopleDirectory').append(
            "<tr>"
            + "<td>" + membObj.name + "</td>"
            + "</tr>"
    );
});

//end table
$('#peopleDirectory').append("</tbody></table>");

我创建表和标题行,然后在关闭表之前迭代返回的JSON以创建表行.但是,如果我使用jQuery $('#peopleDirectory').html(),它将产生表头,然后关闭表,然后从JSON附加行(并且表显示不正确)

I create the table and the header row, and then iterate the returned JSON to create the table rows, before closing the table. However, if I use the jQuery $('#peopleDirectory').html() then it produces the table header, then closes the table, and then appends the rows from the JSON (and the table does not appear correctly)

任何人都可以帮我解决为什么按此顺序执行附加操作吗?

Can anyone help me out with why its executing the appends in this order?

推荐答案

此处的问题可能是您无法像执行操作一样将部分HTML追加到元素中.当您添加<table><tbody>时,浏览器实际上也会关闭标签.然后,当您添加tr等时,它不再存在于表中,浏览器将再次尝试更正它,从而生成损坏的标记.

The problem here is probably that you can't append partial HTML to an element like you're doing. When you append <table><tbody>, the browser will actually close the tags too. Then, when you append trs etc., it's no longer inside the table, and the browser will again attempt to correct it, generating broken markup.

您需要先构造整个标记,然后再附加整个标记.

You need to first construct the entire markup and only after that append it.

类似的事情应该起作用:

Something like this should work:

var html = "<table><thead><tr><th>column header!</th>"
         + "</tr></thead><tbody>";

$.each(jsonArray.members, function(i, membObj) {
    html += "<tr>"
          + "<td>" + membObj.name + "</td>"
          + "</tr>";
});

html += "</tbody></table>";

$('#peopleDirectory').append(html);

这篇关于Javascript/jQuery执行顺序问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆