首页 > 解决方案 > 使用 jQuery 将标题元素转换为链接的最佳方法

问题描述

我想在不使用插件的情况下自动将 WordPress 帖子中的所有标题转换为链接。

Wordpress 帖子的 HTML 结构基本上是这样的:

<article>
  <p>Text</p>
  <h2>Headline</h2>
  <p>More text</p>
  <h3>Another headline</h3>
  <p>Some more text</p>
</article>

现在我有以下 jQuery 来查找 h2 和 h3 的所有实例并将它们转换为链接:

$('article h2').each(function(){

    $(this).replaceWith( "<a href='#' class='something'><h2>" + $(this).html() + "</h2></a>" );

});

$('article h3').each(function(){

    $(this).replaceWith( "<a href='#' class='something'><h3>" + $(this).html() + "</h3></a>" );

});

它工作得很好,但必须有一种更优雅、更高效的方式。

我实际上并不知道如何在 jQuery 中编写代码,而是使用我在其他答案中找到的一些代码将上面的代码组合在一起。 您可以在 jsFiddle 上测试上面的代码

标签: jquery

解决方案


您可以进行两项调整来改进逻辑。

首先,使用 .将所有标题包含在单个选择器中:header。其次,您可以使用wrap()将现有内容放置在a元素中。试试这个:

$('article :header').wrap('<a href="#" class="something"></a>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<article>
  <p>Text</p>
  <h2>Headline</h2>
  <p>More text</p>
  <h3>Another headline</h3>
  <p>Some more text</p>
</article>


推荐阅读