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

时间:2019-06-08 13:19:45

标签: javascript jquery href

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

例如,如果用户输入“ 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链接更改为带有user变量的href。

1 个答案:

答案 0 :(得分:1)

代码查找具有属性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>