简体   繁体   English

利用 Javascript 更改 href 属性

[英]Changing href attribute leveraging Javascript

Currently looking to dynamical change the href attribute on the <a> tag leveraging some Javascript.目前正在寻求利用一些 Javascript 动态更改<a>标签上的href属性。 For context, I want to have a readily available snippet that can do this on a google search in order to highlight a faux user's journey (I work for a company that sells a chatbot tool and the goal is to show how we can make the experience specific to the user if they clicked on an ad).对于上下文,我想有一个现成的片段,可以在谷歌搜索中做到这一点,以突出虚假用户的旅程(我为一家销售聊天机器人工具的公司工作,目标是展示我们如何制作体验特定于用户(如果他们点击了广告)。 This is strictly for demonstration purposes and would not be code I execute outside of my local machine.这严格用于演示目的,不会是我在本地机器之外执行的代码。

I found a code block on another post (cannot seem to locate it now) and have the following:我在另一篇文章中找到了一个代码块(现在似乎无法找到它)并且有以下内容:


function changeHyperlink () {

for (var i = 0; i < anchors.length; i++) {
    anchors[i].href = "www.drift-demo.com"
}
}

changeHyperlink();

This works, however, all the links on the google page have a prepending href attribute of https://www.google.com so all the links now are https://www.google.com/newurl.com .但是,这是有效的,谷歌页面上的所有链接都具有https://www.google.com的前置href属性,因此所有链接现在都是https://www.google.com/newurl.com My end goal is to have all the links be specific to newurl.com .我的最终目标是让所有链接都特定于newurl.com

I don't know how this happening as all the href attributes (in the HTML code) are newurl.com .我不知道这是怎么发生的,因为所有的href属性(在 HTML 代码中)都是newurl.com

When setting the href , include the protocol, eg http or https :设置href ,包括协议,例如httphttps

 const anchors = document.querySelectorAll('a'); function changeHyperlink() { for (var i = 0; i < anchors.length; i++) { anchors[i].href = "https://www.drift-demo.com"; } } changeHyperlink();
 <a>some anchor</a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM