简体   繁体   中英

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? the scenario was i have 3 links i want to get the element by tagname? 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. tahnks

You can use jQuery

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

Pure 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/

As far as I know querySelectorAll is faster than getElementsByTagName or either JQuery selector.

  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. 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. Also, you would change the event from onmouseover to whatever suits your needs. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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