[英]jQuery replace content in a table
我有一个表格,呈现给包含网站链接的页面。 这允许用户轻松点击它并导航等。
我正在构建一个可以将表传递给它的函数,它将数据导出到excel。
这部分的第一部分是创建此表数据的变量,并从列中删除链接,只留下文本。
这是我的表:
<table id="assignedOpenProjects">
<thead>
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bob</td>
<td>1234</td>
<td><a href="http://www.google.com">Link</a></td>
</tr>
</tbody>
</table>
表中的第3列是包含链接的列(基于0的第2列)。
我的jQuery:
// Define the HTML of the table
var table = $('#assignedOpenProjects').prop('outerHTML');
// Loop over all of the table rows
$(table).find('tbody > tr').each(function () {
// Loop over the column that contains the link
$(this).children("td").eq(2).each(function () {
// Define the value of that column
var col = $(this).html();
// Replace the value with the text version
$(col).replaceWith($(col).text());
});
});
// Output the table
$('#output').empty().append(table);
当我运行它时,内容是相同的,它不会删除链接。 但是,如果我将$(col).text()
到控制台,它会显示我期望要替换的列。
有人可以告诉我,为什么这些内容没有像我期望的那样被替换,我做错了什么?
预期结果应该只在输出中包含一次Col3中的单词Link
。
JS小提琴: https : //jsfiddle.net/zrpe8c3x/2/
您正在采取的检索表格的HTML并将其黑客攻击的方法过于复杂。 从你的描述,你正在试图做的一切是从删除的链接功能a
元素,但保留文本。 如果是这种情况,您可以使用unwrap()
将其unwrap()
简单的单行程序:
$('#assignedOpenProjects').find('a').contents().unwrap();
您的代码无效,因为您使用outerHTML
初始化table
变量,但之后不会对其进行修改,因此您在代码末尾添加的内容与之前定义的变量相同,不变,这是相同的你有一个表作为输入
这是因为您的代码中存在以下问题:
您最后附加的table
变量是plain outerHTML
而不是您构建和遍历的jQuery对象
你正在更改一个新的td
对象,它永远不会被附加到原始的td
,所以你最终改变你不使用的东西
这是你的代码纠正了两件事:
$('[name=clean]').click(function(){
// Define the HTML of the table
var table = $('#assignedOpenProjects').prop('outerHTML');
var table2 = $(table);
// Loop over all of the table rows
table2.find('tbody > tr').each(function () {
// Loop over the column that contains the link
$(this).children("td").eq(2).each(function () {
// Define the value of that column
var col = $(this);
// Replace the value with the text version
$(col).replaceWith($(col).text());
});
});
// Output the table
$('#output').empty().append(table2);
});
https://jsfiddle.net/qs3mk7xn/
话虽如此,我相信你应该注意罗瑞的回答。 如果你想要他做同样的事情,但在另一张桌子上,你可以这样做:
$('[name=clean]').click(function(){
$('#output').empty().append($('#assignedOpenProjects').clone().find('a').contents().unwrap().parents().last());
});
https://jsfiddle.net/qs3mk7xn/1/
或者,更有效率,这样的事情:
$('[name=clean]').click(function(){
var clon = $('#assignedOpenProjects').clone();
clon.find('a').contents().unwrap();
$('#output').empty().append(clon);
});
https://jsfiddle.net/qs3mk7xn/2/
或者,如果你只想要第三个td
,就像这样:
$('[name=clean]').click(function(){
var clon = $('#assignedOpenProjects').clone();
clon.find('tbody tr td:nth-child(3) a').contents().unwrap();
$('#output').empty().append(clon);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.