【问题标题】:jQuery: How to find every <a> tags without link/href and replace the href with its text?jQuery:如何在没有链接/href 的情况下找到每个 <a> 标签并用其文本替换 href?
【发布时间】:2018-09-22 23:16:08
【问题描述】:

我有这样的场景,在一个页面中有一些 &lt;a&gt; 标签没有任何 href 链接。

我要做的是找到那些&lt;a&gt; 标签并获取他们的text 并使用他们的text 为他们创建一个href attribute

到目前为止我已经尝试过了,但我收到了这个错误:

Uncaught TypeError: Cannot read property 'attr' of 

我当前的代码:

$(document.body).find("a:not([href])").contents().this.attr('href').this.attr('href').replace('htt://google.com', '');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>An unarmed man was shot in Southwest <a>Atlanta</a>, and <a href='stackoverflow.com'>Panthersville</a> residents want answers.

有人可以就这个问题提出建议吗?

这不是 CSS 问题!!

【问题讨论】:

  • @Mike'Pomax'Kamermans,CSS?!真的吗?
  • 无论谁将此问题标记为完全不相关问题的重复项,都应该解释为什么他们觉得这是一个重复项!
  • @Mike'Pomax'Kamermans,不管是不是CSS,这个问题和CSS无关,jQuery肯定不是CSS。
  • jQuery 可以操作 CSS,但它又不是 CSS,问题不是“我如何使用 CSS 来做到这一点”或任何与 CSS 相关的东西。

标签: javascript jquery


【解决方案1】:

应该这样做:

$('a:not([href])').each(function(){
    $(this).attr('href', $(this).text())
})

$('a:not([href])').each(function() {
  $(this).attr('href', $(this).text())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>An unarmed man was shot in Southwest <a>Atlanta</a>, and <a href='stackoverflow.com'>Panthersville</a> residents want answers.
<p>An unarmed man was shot in Southwest <a>Chicago</a>, and <a href='stackoverflow.com'>Panthersville</a> residents want answers.

这会遍历所有没有 href 属性的锚点,并使用锚点的文本创建属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-21
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    相关资源
    最近更新 更多