I am trying to use jQuery to wrap the text of a <td>
element in an <a>
element but there is also a <span>
element nested inside of the <td>
that I do not want to include in the <a>
element.
Here is a link to a jsfiddle with an example of my issue
中换行文字<style>
td {
background-color: #bada55;
}
</style>
<table>
<tr>
<td class="item"><span> + </span>First</td>
<td class="item"><span> + </span>Second</td>
<td class="item"><span> + </span>Third</td>
</tr>
</table>
$(".item").wrapInner("<a href='#'/>");
答案 0 :(得分:3)
您可以使用以下内容将文本包裹在范围旁边:
$('.item').contents().filter(function() {
return this.nodeType == 3;
}).wrap("<a href='#'/>");
&#13;
td {
background-color: #bada55;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td class="item"><span> + </span>First</td>
<td class="item"><span> + </span>Second</td>
<td class="item"><span> + </span>Third</td>
</tr>
</table>
&#13;
这样做是通过类项循环表单元格,获取单元格的内容(span元素和文本节点),仅返回文本节点,并用锚包装它。