javascript - 使用javascript设置页面上的所有链接

标签 javascript jquery href

我建立了一个网站,将用户输入存储在一个 javascript 变量中,我想将页面上的所有链接(使用 javascript)设置为每个标签中包含的 href,并与用户输入连接。

例如,如果用户输入“aaa”,然后单击指向主页的链接(href="/home"),那么我希望该链接使用“/homeaaa”

我试过:

$(document).ready(function () {
$('a[href]').click(function(){
    oldlink = $(this).attr("href");
    newlink = oldlink.concat(window.uservariable);
    document.links.href = newlink;
})
})

$(document).ready(function () {
$('a[href]').click(function(){
    oldlink = $(this).attr("href");
    newlink = oldlink.concat(window.uservariable);
    $(this).href = newlink;
})
})

但都不起作用。当用户点击它时,都不会将 href 链接更改为与 uservariable 连接的 href。

最佳答案

代码找到所有具有属性 href 的标签并更新值

function myFunction() {
  var x = document.querySelectorAll("a");

  x.forEach(function(item){
  	var val = item.getAttribute("href");
    item.setAttribute("href", val + "aaa");
    console.log(item.getAttribute("href"))
        
  });
 
}
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
  border: 1px solid black;
  margin: 5px;
}
</style>
</head>
<body>

<div id="myDIV">
 <a href="/okety">Oekye</a>
  <h2 class="example">A heading with class="example" in div</h2>
  <p class="example">A paragraph with class="example" in div.</p> 
  <a href="/home">Oekye</a>
</div>

<p>Click the button to add a background color to the first element in DIV with class="example" (index 0).</p>

<button onclick="myFunction()">Try it</button>

<p><strong>Note:</strong> The querySelectorAll() method is not supported in Internet Explorer 8 and earlier versions.</p>



</body>
</html>

或者点击链接

function myfunc2 (event,obj) {	
	event.preventDefault();
	var val = obj.getAttribute("href")
    obj.setAttribute("href", val + "aaa");
    console.log(obj.getAttribute("href"));
    //window.open("your attribut link")
}
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
  border: 1px solid black;
  margin: 5px;
}
</style>
</head>
<body>

<div id="myDIV">
 <a href="/okety" onclick="myfunc2(event,this);">Oekye</a>
  <h2 class="example">A heading with class="example" in div</h2>
  <p class="example">A paragraph with class="example" in div.</p> 
  <a href="/home" onclick="myfunc2(event,this);">Oekye</a>
</div>

<p>Click the button to add a background color to the first element in DIV with class="example" (index 0).</p>



<p><strong>Note:</strong> The querySelectorAll() method is not supported in Internet Explorer 8 and earlier versions.</p>

</body>
</html>

关于javascript - 使用javascript设置页面上的所有链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56506788/

相关文章:

javascript - 脚本只运行一次

javascript - 对具有相同类的元素应用 Jquery .one 函数

javascript - 请求中包含的安全 token 无效。 AWS 开发工具包

javascript - 在更改的 map 上动态添加标记 - Google Maps API

javascript - 如何抓取页面上的某些文本?

python - 用于 html 文本中链接的正则表达式

css - href 乱七八糟的 css 动画

html - 是否可以为箭头制作具有更大底部填充的 href

javascript - 我的页面无法加载(ReactJS)

javascript - 如何在 Ionic 应用程序中访问 .io-config.json 文件值