jquery - 使用 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 上测试上面的代码。
解决方案
您可以进行两项调整来改进逻辑。
首先,使用 .将所有标题包含在单个选择器中: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>
推荐阅读
- c# - 测试范围时是否有更多的 C# 9 / .NET 5 惯用方式来表达 If/Else?(模式匹配或更新的 C# 功能)
- apache-spark - 在火花中,我如何将一列添加到具有该列中唯一值及其频率的频率图中
- reactjs - React JS 中的奇怪行为
- apache-nifi - NIFI 大量工作流配置和执行策略
- r - 替换特定字符值不起作用
- bokeh - 如何修改 DateTimeTickFormatter 类?
- javascript - 如何使用正则表达式在字符串中查找数学?
- python-3.x - 无法使用python在文本文件中的短语中定位单词
- c++ - 访问树中的右节点指针(引用指针)时出错
- python - 如何使用函数(def)消除冗余?