简体   繁体   English

如何使用JavaScript获取链接onclick的ID?

[英]how to get the id of a link onclick using javascript?

Hi may i know how can i get my id of my links using javascript? 嗨,我可能知道如何使用javascript获取链接的ID? the scenario was i have 3 links i want to get the element by tagname? 场景是我有3个链接,我想按标记名获取元素? is it possible? 可能吗?

<a href="docview.php?id=25" id="1">July 3, 2013</a>
<a href="docview.php?id=26" id="2">July 10, 2013</a>
<a href="docview.php?id=27" id="3">July 17, 2013</a>

I want to display the ID of my link the one i chose and then when i click n 2nd link the id of the second link will display. 我想显示我选择的链接的ID,然后单击n第二个链接时,将显示第二个链接的ID。 tahnks 吊车

You can use jQuery 您可以使用jQuery

 $("a").click(function(){
    alert(this.id);
    });

Pure JS: 纯JS:

var elements = document.querySelectorAll("a");
for (var i = 0; i < elements.length; i++)
{
    elements[i].addEventListener("click", function() {
        console.log(this.id)
    }, true);
}

http://jsfiddle.net/6NXC7/1/ http://jsfiddle.net/6NXC7/1/

As far as I know querySelectorAll is faster than getElementsByTagName or either JQuery selector. 据我所知, querySelectorAllgetElementsByTagName或JQuery选择器要快。

  var anchor = document.getElementsByTagName('a');
  for(var i=0;i<anchor.length;i++){
     anchor[i].addEventListener("click", function() {
       alert(this.id);
        return false;
    }
  }

You can try the following: the function is called when the link is clicked(you can also use other events such as onmouseover) it passes the id of the element to the function and prints it to the screen. 您可以尝试以下操作:单击链接时调用该函数(您也可以使用其他事件,例如onmouseover),它将元素的ID传递给该函数并将其打印到屏幕上。 Hope this helps. 希望这可以帮助。

<!DOCTYPE html>
<html>
<body>

<a href="docview.php?id=25" id="1" onclick="myFunction('1')">July 3, 2013</a>
<a href="docview.php?id=26" id="2" onclick="myFunction('2')">July 10, 2013</a>
<a href="docview.php?id=27" id="3" onclick="myFunction('3')">July 17, 2013</a>

<script>

function myFunction(id) {
 var x=document.getElementById(id);
document.write(x.id);

}
</script>

</body>
</html>

Here is the code for changing the value of the label... 这是更改标签值的代码...

<!DOCTYPE html>
<html>
<body>

<a href="docview.php?id=25" id="1" onmouseover="myFunction('1')">July 3, 2013</a>
<a href="docview.php?id=26" id="2" onmouseover="myFunction('2')">July 10, 2013</a>
<a href="docview.php?id=27" id="3" onmouseover="myFunction('3')">July 17, 2013</a>

<script>
var newString = "this is the new string";
function myFunction(id) {
document.getElementById(id).innerHTML = newString;

}
</script>

</body>
</html>

the innerHTML property appends the current text to whatever you specify. innerHTML属性将当前文本追加到您指定的任何内容。 Also, you would change the event from onmouseover to whatever suits your needs. 另外,您可以将事件从onmouseover更改为适合您需要的任何事件。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM