简体   繁体   中英

get specific data of multiple same class name jquery

hi im just learn jquery a bit i have an html code

<a class="num" href="#" data="number1"> number1 </a>
<a class="num" href="#" data="number2"> number2 </a>
<a class="num" href="#" data="number3"> number3 </a>
<a class="num" href="#" data="number4"> number4 </a>
<a class="num" href="#" data="number5"> number5 </a>

how do i get the data from third item if i clicked it? i already done something like this:

$('.num').click(function(){
  var datas = $('.num').attr('data');
  alert(datas)
})

and it keep alert "number1" even i clicked the 4th or 5th item? anything wrong with my code?

You have to use this to refer current clicked link

$('.num').click(function(){
  var datas = $(this).attr('data');
  alert(datas)
})

Working snippet

 $('.num').click(function(){ var datas = $(this).attr('data'); alert(datas) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="num" href="#" data="number1"> number1 </a><br> <a class="num" href="#" data="number2"> number2 </a><br> <a class="num" href="#" data="number3"> number3 </a><br> <a class="num" href="#" data="number4"> number4 </a><br> <a class="num" href="#" data="number5"> number5 </a> 

You should refer to this to refer to the clicked <a> - then, you can access its data attribute:

 $('.num').click(function() { console.log( $(this).attr('data') ); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="num" href="#" data="number1"> number1 </a> <a class="num" href="#" data="number2"> number2 </a> <a class="num" href="#" data="number3"> number3 </a> <a class="num" href="#" data="number4"> number4 </a> <a class="num" href="#" data="number5"> number5 </a> 

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