【问题标题】:Change href in HTML tag does not works更改 HTML 标记中的 href 不起作用
【发布时间】:2018-11-25 05:06:56
【问题描述】:

我有这个 HTML 标签:

<a href="show_comments.php?id=6">(show comments)</a>

我想更改它的href。我正在尝试使用 jquery,但它不起作用:

$('a[href="show_comments.php?id=6"]').attr('href', 'xyz.php');

我也尝试了 querySelectorAll:

document.querySelectorAll("a[href='show_comments.php?id=6']").setAttrtibute('href','xyz.php');

更新:

这是一个时间问题。使用 $( document ).ready(function() {});两种解决方案都有效。

为什么这些解决方案不起作用?我想在没有 jQuery 的情况下这样做,但任何解决方案都值得赞赏。

【问题讨论】:

  • 究竟是什么不在这里工作?
  • 我找到了解决方案。主要问题是在页面加载之前执行的脚本标签。 :)

标签: javascript jquery html href


【解决方案1】:

尝试给这个元素添加一个 id,然后在 jQuery 中或通过播放 JS 选择这个 id

假设标签有一个名为changeUrl的id

$("#changeUrl").attr('href', 'xyz.php');

document.querySelector("#changeUrl").setAttrtibute('href','xyz.php');

【讨论】:

  • .changeUrl 是一个类,而不是一个 id。如果需要,您可以将其设为 id,但您的示例代码未使用 id。此外,提供更新的 HTML 代码并添加 id/class 会很有帮助。
【解决方案2】:

当您使用 querySelectorAll 时,您必须在每个节点上单独执行此操作,因为它会返回一个没有 setAttribute 方法的 NodeList。只有节点有这个方法:

document.querySelectorAll("a[href='show_comments.php?id=6']").forEach(node => node.setAttrtibute('href','xyz.php'))

编辑:如果您只有一个节点,请使用document.querySelector

document.querySelector("a[href='show_comments.php?id=6']").setAttrtibute('href','xyz.php')

&lt;/body&gt; 之前加载你的 JS 以确保 JS 可以访问完整的 DOM

【讨论】:

  • jQuery 的情况并非如此
  • 非常感谢!!它有很大帮助。我也使用 $( document ).ready(function()});在页面加载后执行它。谢谢:)
  • @charlietfl 是的,我错过了那个细节。但是 OP 回答说他之前正在加载脚本,所以现在很好
【解决方案3】:

已解决: 这是一个时间问题。使用$( document ).ready(function() {}); 两种解决方案都有效。

问题是它是CSRF攻击,所以必须加载html才能成功攻击(我要更改的标签是在JS脚本之后加载的)。

【讨论】:

    猜你喜欢
    • 2013-02-27
    • 1970-01-01
    • 2013-11-22
    • 2010-11-18
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多