jQuery 关闭打开标签
在尝试将 xml 文件解析为表格格式时,jQuery 不断关闭我的打开 标记。有解决办法吗?
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "sample-data.xml",
dataType: "xml",
success: parseXml
});
});
function parseXml(xml)
{
$(xml).find("user").each(function()
{
var id = "#sortable";
$(id).append("<tr>");
$(id).append("<td>" + $(this).find("name").text() + "</td>");
$(id).append("</tr>");
});
}
</script>
<table id="table" class="tablesorter">
<thead>
<tr>
<th>test</th>
</tr>
</thead>
<tbody id="sortable">
</tbody>
</table>
这就是标记的输出方式:
<tr></tr>
<td>data</td>
While trying to parse an xml file into table format, jQuery keeps closing my opening <tr>
tag. Is there a work around for this?
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "sample-data.xml",
dataType: "xml",
success: parseXml
});
});
function parseXml(xml)
{
$(xml).find("user").each(function()
{
var id = "#sortable";
$(id).append("<tr>");
$(id).append("<td>" + $(this).find("name").text() + "</td>");
$(id).append("</tr>");
});
}
</script>
<table id="table" class="tablesorter">
<thead>
<tr>
<th>test</th>
</tr>
</thead>
<tbody id="sortable">
</tbody>
</table>
This is how the markup is being outputted:
<tr></tr>
<td>data</td>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需调用 1 个追加而不是多个追加。
将此部分:更改
为:
Simply call 1 append instead of multiple appends.
Change this part:
to this:
我建议不要在循环上使用追加。相反,将其输出到循环之外。
如果您要在循环内多次使用 $(this),例如年龄、性别等,我建议您将变量分配给 $(this),而不是一遍又一遍地调用 $(this)。
PS我没有测试该代码,只是想提出一些建议......但希望它能起作用。干杯^^
I'd suggest to not use append on the loop. Instead, output it outside the loop.
In cases that you're going to use $(this), many times inside the loop, like for age, gender etc, I suggest you assign a variable to $(this) instead of calling $(this) over and over again.
P.S I didn't test that code, just want to suggest something... but hope it works. Cheers ^^
是的,jQuery 并不能真正实现这一点。试试这个:
Yeah, jQuery doesn't really work that. Try this:
我不认为 jQuery 是这里的罪魁祸首。
当您调用
append("")
时,您希望它做什么?答案:您希望它根据您的规范修改 DOM。但是,DOM 是一种数据结构,而不是字符串。您无法将“未关闭”元素添加到 DOM,因此所有元素在添加时本质上都是关闭的。因此,后续的
append("...")
将在之后添加 TD 元素;
而不是在它的内部。此外,任何append("")
的尝试都会被忽略,因为考虑到append("")
的处理,这将是相当无意义的>。I don't think that jQuery is the culprit here.
When you call
append("<tr>")
, what do you want it to do? Answer: You want it to modify the DOM per your specification. But, the DOM is a data-structure, not a string. You cannot add an "unclosed" element to the DOM, so all elements are inherently closed at the time they are added.As a result, the subsequent
append("<td>...</td>")
is adding the TD element after the<tr>
rather than inside of it. Furthermore, any attempt toappend("</tr>")
is simply ignored since it would be rather nonsensical given the handling ofappend("<tr>")
.