如何使用javascript / css更改href属性的值? [英] how can the value of an href attribute be changed using javascript/css?

查看:166
本文介绍了如何使用javascript / css更改href属性的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设html包含以下结构:

Assuming that the html contains the following structure:

<div>
    <a href="http://the/link/that/needs/to/be/changed">text</a>
</div>

<div>
    <div>
        //<script> or <style> must go here
    </div>
</div>

...,并假定对最终HTML文件的贡献只能插入到指定的位置,并假定 a元素的标记不能以任何方式修改,是否可以添加JavaScript或CSS代码来更改前 a元素的href属性所引用的url?如果是这样,怎么办?

...and assuming that the 'contribution' to the final HTML file can be inserted ONLY at the specified location, and assuming that the markup for the "a" element cannot be modified in any way, is it possible to add javascript or css code that will change the url that the href attribute of the previous "a" element refers to? If so, how?

推荐答案

您可以在没有id的情况下进行操作:

You could do it without id:

document.querySelector("a[href^='http://the']")

并设置href属性:

document.querySelector("a[href^='http://the']").href=whatever

的任何内容(浏览器-兼容性)的 querySelector 参见 MDN条

For a full reference (browser-compatibility) of querySelector see the MDN-Article

这篇关于如何使用javascript / css更改href属性的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆