将部分代码添加到 jquery 中的 td
Add part of code to a td in jquery
我在将一些使用 jQuery 的 HTML 代码添加到现有 table
中的 td
元素时遇到了一点问题。我的 HTML 代码是:
<table>
<tbody>
<tr>
<td>Something</td>
<td><strong>10</strong></td>
</tr>
</table>
</tbody>
现在我已经编写了这段 jQuery 代码以在包含 'Something':
的单元格中添加工具提示
$('table tr').each(function(){
if ($(this).find('td').text() == 'Something') {
$(this).html('<td><a class="tooltips" title="bla bla bla bla">Something</a></td>')
}
});
在这种情况下,jQuery 函数可以正常工作,我在 td
内容中添加了一个工具提示,但第二个 td
元素被删除了。我试过使用 .find('td:first')
但无论如何第二个 td
消失了。
谁能告诉我如何正确编写 jQuery 代码,以便第二个 td
留在页面中?非常感谢您的帮助。
问题是因为您覆盖了 tr
元素中的所有 HTML,而不仅仅是替换包含 Something
文本值的第一个 td
。试试这个:
$('table td').each(function(){
if ($(this).text() == 'Something'){
$(this).replaceWith('<td><a class="tooltips" title="bla bla bla bla">Something</a></td>');
}
});
您通过 $(this)
访问并使用 .html()
.
完全清除了 <tr>s
内容
$(this).html( '<td><a class="tooltips" title="bla bla bla bla">Something</a></td>' );
所以在这一行中,第二个td
也被抹掉了。因为您正在遍历每个 <tr>
.
你必须遍历每个 <td>
我在将一些使用 jQuery 的 HTML 代码添加到现有 table
中的 td
元素时遇到了一点问题。我的 HTML 代码是:
<table>
<tbody>
<tr>
<td>Something</td>
<td><strong>10</strong></td>
</tr>
</table>
</tbody>
现在我已经编写了这段 jQuery 代码以在包含 'Something':
的单元格中添加工具提示$('table tr').each(function(){
if ($(this).find('td').text() == 'Something') {
$(this).html('<td><a class="tooltips" title="bla bla bla bla">Something</a></td>')
}
});
在这种情况下,jQuery 函数可以正常工作,我在 td
内容中添加了一个工具提示,但第二个 td
元素被删除了。我试过使用 .find('td:first')
但无论如何第二个 td
消失了。
谁能告诉我如何正确编写 jQuery 代码,以便第二个 td
留在页面中?非常感谢您的帮助。
问题是因为您覆盖了 tr
元素中的所有 HTML,而不仅仅是替换包含 Something
文本值的第一个 td
。试试这个:
$('table td').each(function(){
if ($(this).text() == 'Something'){
$(this).replaceWith('<td><a class="tooltips" title="bla bla bla bla">Something</a></td>');
}
});
您通过 $(this)
访问并使用 .html()
.
<tr>s
内容
$(this).html( '<td><a class="tooltips" title="bla bla bla bla">Something</a></td>' );
所以在这一行中,第二个td
也被抹掉了。因为您正在遍历每个 <tr>
.
你必须遍历每个 <td>