简体   繁体   中英

JQuery Get ID of clicked link

I've got this type of link in my HTML :

Librairy :

<script type="text/javascript" src="../../resources/js/jquery/jquery-1.12.3.min.js"></script>

HTML :

<a id='1' href='#' class='bulletinLink'> Bulletin du 11-01-2015 </a>
<a id='2' href='#' class='bulletinLink'> Bulletin du 13-02-2015 </a>
...

I want to get the id of this link when I click, this is my jQuery:

$(function() {
$('.bulletinLink').on('click',function(event){
    var id = $(this).attr('id');
    alert(id);
})
});

When I click in the link, it doesn't fire the jQuery function, what am I missing?

You could use the following simplified version, where you use this.id to retrieve the attribute id for your DOM without re-querying it.

PS: Make sure you have included jQuery in your page . Example:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

 $(function() { $('.bulletinLink').on('click', function(event) { alert(this.id); }) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a id='1' href='#' class='bulletinLink'> Bulletin du 11-01-2015 </a><br> <a id='2' href='#' class='bulletinLink'> Bulletin du 13-02-2015 </a> 

It is working fine with following code

 $(function() { $('.bulletinLink').on('click', function(event) { alert($(this).attr("id")); }) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a id='1' href='#' class='bulletinLink'> Bulletin du 11-01-2015 </a><br> <a id='2' href='#' class='bulletinLink'> Bulletin du 13-02-2015 </a> 

you need to add jQuery library...

Use this one :

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

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