Javascript HTML标记中的更改href无效

Javascript HTML标记中的更改href无效,javascript,jquery,html,href,Javascript,Jquery,Html,Href,我有这个HTML标签: <a href="show_comments.php?id=6">(show comments)</a> 我还尝试了querySelectorAll: document.querySelectorAll("a[href='show_comments.php?id=6']").setAttrtibute('href','xyz.php'); 更新: 这是一个时间问题。使用$document.readyfunction{};两种解决方案都有效 为什

我有这个HTML标签:

<a href="show_comments.php?id=6">(show comments)</a>
我还尝试了querySelectorAll:

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

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


为什么这些解决方案不起作用?我希望在没有jQuery的情况下执行此操作,但任何解决方案都值得赞赏。

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

document.querySelectorAll("a[href='show_comments.php?id=6']").forEach(node => node.setAttrtibute('href','xyz.php'))
编辑:如果只有一个节点,请使用document.querySelector


在加载之前加载JS,以确保JS有权访问完整的DOM

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

让我们假设标记有一个名为changeUrl的id

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

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


问题是这是一种CSRF攻击,因此必须加载html才能成功攻击我想更改的标记在JS脚本加载后加载。

jQuery案例并非如此,但非常感谢!!这很有帮助。我还使用$document.readyfunction};在页面加载后执行它。谢谢:@charlietfl是的,我错过了那个细节。但是OP回答说他之前在加载脚本,所以现在没事了,这里到底有什么不起作用?我已经找到了解决方案。主要问题是在加载页面之前执行了脚本标记。:。changeUrl是一个类,而不是id。如果需要,可以将其设置为id,但示例代码没有使用id。此外,使用添加的id/类提供更新的HTML代码也会很有帮助。
document.querySelector("a[href='show_comments.php?id=6']").setAttrtibute('href','xyz.php')
$("#changeUrl").attr('href', 'xyz.php');
document.querySelector("#changeUrl").setAttrtibute('href','xyz.php');