How to get HTML tag data attributes in jquery

时间:2015-06-30 13:41:06

标签: jquery html

I have the following Html code:

<tr>
   <td><a href="#" class="block" serverid="@storedServerId"></a></td>
<tr/>

But how can I get the 'serverid' attribute's value to use in my jQuery script?

This is what I tried:

var srv= document.getElementById('storedServerId').value;

But it returns simple text not the vlaue!

Thanks,

4 个答案:

答案 0 :(得分:2)

To get attributes in Jquery,use

$("your-id").attr("your-attr");

WHILE for your HTML 5 data-* attributes, you could use,

$("your-id").data("your-attr");

In your case,it would be.

var j=$(".block").attr("serverid");
alert(j);

答案 1 :(得分:1)

To use data attribute you have to add data-serverid in your anchor And you can get it in jquery by data() function.

  <tr>
       <td><a href="#" class="block" data-serverid="@storedServerId"></a></td>
<tr/>

$(document).ready(function(){
 alert($('a').data('serverid'));
})

答案 2 :(得分:0)

这是从多个类获取属性的方法:

function getServerID() {

        var sid = $('.block').each(function () {

           alert($(this).attr('serverid'));
        });

答案 3 :(得分:-1)

HTML

<tr>
<td><a href="#" class="block" data-serverid="@storedServerId"></a></td>
<tr/>

jQuery

$('.block').data('serverid')

gets you value of your data attribute

http://jsfiddle.net/2rowezve/