我想用一个包装好的td
替换一个table
的每个a
标记,它的内部有一个a
标记:
$("td").each(function() {
if ($(this).find("a").length) {
var link = $(this).find("a").attr('href');
$("a").contents().unwrap();
var content = $(this).html();
$(this).replaceWith("<td class='link'><a href='" + link + "'> " + content + "</a></td>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<p>Some text</p>
<p>Some <a href="http://www.mynewlink.tld">more text</a></p>
</td>
<td>
<p>Some text</p>
<p>Some <a href="http://www.mynewotherlink.tld">more text</a></p>
</td>
</tr>
</table>
但它只做第一个。但我希望每个人都能被替换。有人能处理这事吗?
发布于 2017-04-27 09:16:38
您可以使用wrapInner
将td
中的所有内容都包装成a
。您的$("a").contents().unwrap();
实际上破坏了您的代码,因为它打开了每个a
标记,而不是一个。因此,在包装完所有内容之后,您必须手动锁定这些a
标记。
有关工作示例,请参阅下面。
$("td").each(function() {
if ($(this).find("a").length) {
var link = $(this).find("a").attr('href');
$(this).wrapInner( "<a href='" + link + "'/>");
$(this).addClass("link");
}
});
$("td a a").contents().unwrap();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<p>Some text</p>
<p>Some <a href="http://www.mynewlink.tld">more text</a></p>
</td>
<td>
<p>Some text</p>
<p>Some <a href="http://www.mynewotherlink.tld">more text</a></p>
</td>
</tr>
</table>
发布于 2017-04-27 09:27:01
代码中的问题是
$("a").contents().unwrap();
当它第一次执行时,它将所有锚标记元素替换为纯文本。因此,下一次迭代时,它无法找到任何锚标记。这就是为什么它只发生在第一个元素上。因此,请按下面的方式更改代码
$(this).find("a").contents().unwrap();
发布于 2017-04-27 10:01:29
给你..。用"a“标签包装所有的子标记,而不是将其全部包装在一个标记中。
$("td").each(function() {
var anchor = $(this).find("a");
if (anchor.length) {
var link = anchor.attr('href');
anchor.contents().unwrap(); // unwrap link tag
$(this).children().wrapInner( "<a href='" + link + "'/>" );
$(this).addClass("link");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<p>Some text</p>
<div>Some text</div>
<p>Some <a href="http://www.mynewlink.tld">more text</a></p>
</td>
<td>
<p>Some text</p>
<p>Some <a href="http://www.mynewotherlink.tld">more text</a></p>
</td>
</tr>
</table>
https://stackoverflow.com/questions/43653403
复制相似问题