我建立了一个网站,将用户输入存储在一个 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/