简体   繁体   中英

alert the ID of the Link the User Clicks On

I have a couple links that each have unique IDs. I want to call a single function that when anyone of the links is clicked, the user gets an alert that says the link ID. I am stumped. Here's what I have. I want to do this with pure JavaScript.

My code:

<p><a href="#" id="link0">Link0</a></p>
<p><a href="#" id="link1">Link1</a></p>
<p><a href="#" id="link2">Link2</a></p>
<p><a href="#" id="link3">Link3</a></p>

<script>
function test(i) {
    alert("You just clicked on link:" + i); 
}

onclick = function () { 
    test(i);
};
</script>

Try this

var links = document.getElementsByTagName( "a" );

for ( var i = 0; i < links.length; i++ ) {
    links[i].addEventListener( "click", function( e ) {
        e.preventDefault();
        alert( this.id );
    }, false );
}

DEMO

I just created an example for you using jQuery.

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

http://jsfiddle.net/Yynw9/

To use jQuery you had to include the library in your header:

<script src="//code.jquery.com/jquery-1.9.1.js" type="text/javascript" />

Here's the javascript you are looking for:

var elements = document.getElementsByTagName("a");
for(var i = 0, length = elements.length; i < length; i++) {
    elements[i].addEventListener( "click", function(e) {
        e.preventDefault();
        alert("You just clicked on link: " + this.id); 
    }, false );
}

JSFiddle: http://jsfiddle.net/3R4FA/1/

The code loops first selects all your elements that are <a> tags. It then loops through this array, and adds a click event listener to each item. The use of the this keyword accesses the element that triggered the event, and then you can fetch the id.

in browsers that support it, you can use querySelectorAll to grab all of the ids which begin with 'link' or you can add a class and use getElementsByClassName.. in legacy browsers, the solution is not as clean, but you can grab all of the 'a' tags in the document or inside of an element, and check if the 'id' attribute starts with 'link'...

function test(i) {
    alert("You just clicked on link:" + this.id); 
}
if (document.querySelectorAll('a[id^="link"]')) {
    var elements = document.querySelectorAll('a[id^="link"]');
    var i = 0;
    for (i = 0; i < elements.length; i += 1) {
        elements[i].onclick = test;
    }
} else {
    var elements = document.getElementsByTagName('a');
    var i = 0;
    for (i = 0; i < elements.length; i += 1) {
        if (elements[i].id.substr(0,4) === 'link') {
            elements[i].onclick = test;
        }
    }
}

http://jsfiddle.net/Xvwme/3/

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