使用jQuery .append构建表格会产生不正确的html [英] Using jQuery .append to build table yielding incorrect html
问题描述
我编写了以下javascript动态创建日历并将其附加到指定的div.它可以正常工作,并且日历在浏览器中看起来也不错.
I wrote the following javascript to dynamically build a calendar and append it to a designated div. It works and the calendar looks fine in the browser.
$('#Calendar').append('<table><thead><th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th><th>Friday</th><th>Saturday</th><th>Sunday</th></thead><tr>');
for (i = 0; i <= loop; i++) {
if ((i == 7) || (i == 14) || (i == 21) || (i == 28) || (i == 35)) {
$('#Calendar').append(loopDate.getDate() + "</tr><tr>");
$('#Calendar').append('<td>' + loopDate.getDate() + '</td>');
loopDate.addDays(1);
} else {
$('#Calendar').append('<td>' + loopDate.getDate() + '</td>');
loopDate.addDays(1);
}
}
$('#Calendar').append('</table>');
}
但是,当我检查页面的结果HTML时,我发现<tr></tr>
不在正确的位置.似乎也有多余的附加内容.有人可以向我解释为什么会这样吗?
However, when I inspect the resulting HTML for the page I see that my <tr></tr>
are not landing in the correct place. There also appears to be an extraneous appended . Can someone please explain to me why this is happening?
<div id="Calendar">
<div></div>
<table>
<thead>
<tr>
<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>
<th>Thursday</th>
<th>Friday</th>
<th>Saturday</th>
<th>Sunday</th>
</tr></thead>
<tbody>
<tr></tr>
</tbody>
</table>
<td>26</td>
<td>27</td>
<td>28</td>
<td>29</td>
<td>30</td>
<td>31</td>
<td>1</td>
<tr></tr>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<tr></tr>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
<td>15</td>
<tr></tr>
<td>16</td>
<td>17</td>
<td>18</td>
<td>19</td>
<td>20</td>
<td>21</td>
<td>22</td>
<tr></tr>
<td>23</td>
<td>24</td>
<td>25</td>
<td>26</td>
<td>27</td>
<td>28</td>
<td>29</td>
</div>
推荐答案
诸如append()
的jQuery方法可操纵浏览器的DOM树.
DOM包含 complete HTML元素.您不能放入标签的一半.
jQuery methods such as append()
manipulate the browser's DOM tree.
The DOM holds complete HTML elements. You can't put in half of a tag.
相反,您可以将HTML连接成一个字符串(或者,为了获得更好的性能,是一个数组),然后立即将完整的HTML字符串放入DOM中.
Instead, you can concatenate HTML into a string (or, for better performance, an array), then put the complete HTML string into the DOM at once.
这篇关于使用jQuery .append构建表格会产生不正确的html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!