установить все ссылки на странице, используя JavaScript - PullRequest
1 голос
/ 08 июня 2019

У меня есть настроенный веб-сайт, на котором пользовательский ввод хранится в переменной 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, когда пользователь щелкает по ней, на ссылку href, связанную с переменной user.

1 Ответ

1 голос
/ 08 июня 2019

Код находит все теги с атрибутом 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>
...