jQuery:替换标签中的每个td

时间:2017-04-27 09:09:32

标签: jquery html

我想将td标记为table的{​​{1}}替换成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>
Preferences > Editor > File and Code Templates > Includes tab > PHP File Header

但它只做第一个。但我希望每一个都被替换。 任何人都可以处理这个吗?

3 个答案:

答案 0 :(得分:1)

您可以使用wrapInnertd中的所有内容与a打包在一起。您的$("a").contents().unwrap();实际上是在破坏您的代码,因为它会解开每个a标记而不是一个标记。因此,在包装完所有内容后,您必须手动定位这些a标记。

请参阅下面的工作示例。

&#13;
&#13;
$("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();
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

代码中的问题是

 $("a").contents().unwrap();

第一次执行时,它将所有的锚标记元素替换为纯文本。因此,下一次迭代它无法找到任何锚标记。这就是为什么它只发生在第一个元素上。所以改变你的代码如下

  $(this).find("a").contents().unwrap();

DEMO

答案 2 :(得分:0)

这里你去..用“ 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>