开发者

get identifier of link given the class jquery

开发者 https://www.devze.com 2023-01-13 06:21 出处:网络
i have this piece of html <li><a href=\"#\" id=\"9000\" class=\"yes vpslink\"><img src=\"x.gif\" /></a></li>

i have this piece of html

<li><a href="#" id="9000" class="yes vpslink"><img src="x.gif" /></a></li>
<li><a href="#" id="9001" class="no vpslink"><img src="x.开发者_Go百科gif" /></a></li>


$('.vpslink').click(function(e) {
   var id='i dont know dude'; 
   alert('you clicked on id'+id);
}); 

How do I find the id of this class, link ?


$('.vpslink').click(function(e) {
   var id= $(this).attr('id'); 
   alert('you clicked on id ' + id);
}); 


Inside the click handler:

alert($(this).attr('id'));


$('.vpslink').click(function(e) {

      // Quick way to get the ID
   var id = this.id;

      // Replace the SRC of the sibling <img> 
   $(this).siblings('img').attr('src', function(i,src) {
        return (src == 'x.gif') ? 'y.gif' : 'x.gif';
   });

});

The fastest way to get the ID of the element is to access its DOM property directly with this.id.

You can use .siblings() to get the sibling <img> and .attr() to update the source. The .attr() method can take a function as a parameter that returns the value to set.

0

精彩评论

暂无评论...
验证码 换一张
取 消