更改 HTML 标签中的 href 不起作用

Change href in HTML tag does not works

我有这个 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');

更新:

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

为什么这些解决方案不起作用?我想在没有 jQuery 的情况下执行此操作,但欢迎提供任何解决方案。

当您使用 querySelectorAll 时,您必须在每个节点上单独执行此操作,因为它 returns 您是一个没有 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')

</body> 之前加载您的 JS 以确保 JS 可以访问完成 DOM

尝试向该元素添加一个 id,然后在 jQuery 或通过播放 JS

选择该 id

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

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

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

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

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