开发者

Javascript table construction bug using JQuery in Firefox on Mac OSX

I'm using some code to build up tables using JQuery, but in Firefox 3.5.3 on Mac OSX, the table cells all appear on separate lines by themselves, instead of in their respective rows. Chrome 5.0.342.7 beta on OSX correctly produc开发者_如何转开发es the table, as does Safari 4.0.5.

Here is a minimal reproduction case:

<html>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function()
{
    var b = $('body');
    b.append("<table>");
    for (var i = 0; i < 3; ++i)
    {
        b.append("<tr>");
        for (var j = 0; j < 3; ++j)
            b.append("<td>x</td>");
        b.append("</tr>");
    }
    b.append("</table>");
});
</script>
</body>
</html>

In Chrome and Safari, I get this correct output:

x x x
x x x
x x x

but Firefox produces:

x
x
x
x
x
x
x
x
x

Note that if I manually create that exact table without using Javascript (i.e. direct into the HTML) then the table appears correctly in Firefox. Also, if I change the JS to append then entire table in one call then it also works -- the only time it doesn't work is if you append it part-by-part as I have done before.

My question is: is this to be expected, or should I report this as a bug to Firefox? I'm pretty sure this is a Firefox bug, but I'm a bit of a newbie to JS and web development in general, so perhaps there's something I'm missing?

P.S. obviously there are easy ways to get around this -- that's not my concern. See above.


You are trying to do to much that jQuery will handle for you try doing this:

var table = $("<table>");
for (var i = 0; i < 3; ++i) {
    var tr = $("<tr>").appendTo(table);
    for (var j = 0; j < 3; ++j)
        $("<td>x</td>").appendTo(tr);
}
table.appendTo('body');

jQuery will handle creating a DOM fragment for you and create your elements for you.


I don't think it makes sense to append the <tr> elements to the body - they're supposed to be inside the table. When you append the <table> element, you're appending a complete table element. To then add random table rows after that really makes no sense.

Do this instead:

var b = $('body'), t = $('<table/>');
for (var i = 0; i < 3; ++i) {
  var tr = $('<tr/>');
  for (var j = 0; j < 3; ++j) tr.append($('<td/>').text("x"));
  t.append(tr);
}
b.append(t);

That way, you're appending the table cell elements to each row, appending each row to the table, and finally appending the table to the body.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜