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

set all links on a page using javascript

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

例如,如果用户输入 "aaa" 然后点击 link 到主页,(with href="/home")那么我想要 link使用“/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 link 更改为与用户变量连接的 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>

或在 link 上单击

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>