[英]How to pass value from href to input
Need some guidance. 需要一些指导。 I am trying to pass a value from href
to an input
value using getAttribute and it works fine, but if I used more than one a
tag it only shows href
attribute for the first one. 我想从一个值传递href
到input
使用的getAttribute值,它工作正常,但如果我使用一个以上的a
标签只显示href
的第一个属性。
Pls, check the code snippet, 请检查代码段,
function myFunction(event) { document.getElementById("demo").value = document.getElementsByTagName("a")[0].getAttribute('href'); }
<a href="#2" onclick="myFunction(event)">test1</a> <a href="#3" onclick="myFunction(event)">test2</a> <input id="demo"></input>
Your problem is the following: 您的问题如下:
// That line is returning always the first <a> element, so you're getting always '#2'.
document.getElementsByTagName("a")[0];
You can learn a little more here Element.getElementsByTagName()
您可以在此处了解更多信息Element.getElementsByTagName()
You can pass the element directly to your function myFunction
. 您可以将元素直接传递给函数myFunction
。
Look this code snippet: 请看以下代码片段:
function myFunction(caller) { document.getElementById("demo").value = caller.getAttribute('href'); }
<a href="#2" onclick="myFunction(this); event.target">test1</a> <a href="#3" onclick="myFunction(this); event.target">test2</a> <input id="demo"></input>
See, now the input is getting the right href
value. 瞧,现在输入得到正确的href
值。
Dynamically, you can do the same thing like this, 动态地,您可以做同样的事情,
var a = document.querySelectorAll("a"); for (var i in a) { a[i].onclick = function() { document.getElementById("demo").value = this.getAttribute("href"); }; }
<a href="#1" >test1</a> <a href="#2" >test2</a> <input id="demo" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.