How would one get a custom attribute with Jquery
We have a custom attribute on checkboxes in this case called data-ref.
How would one get the value. This did not work.开发者_高级运维
this.attr('data-ref');
Any ideas,
Marvellous
You're aware that you have a discrepancy between your custom attribute 'date-ref' in your text, and 'data-ref' in your jQuery?
Also, you might find it easier to work with the jQuery object:
$(this).attr('data-ref');
JS Fiddle demo.
The problem, indeed, seems to be that you weren't using a jQuery object:
this.attr('data-ref');
Can't work
On the other hand, to retrieve data-*
attributes using the DOM, you do have the options of:
this.getAttribute('data-ref');
Or:
this.dataset.ref;
Or:
this.dataset['ref'];
$("selector").attr("data-ref");
Should definitly work.
Maybe you can post your html code.
maybe you must use:
$(this).attr('data-ref');
but this is not very beautiful! use jQuery.data() to store data to DOM nodes.
to store:
$('#divid').data('data-ref', 'i am data');
to get:
var data = $('#divid').data('data-ref');
The previously stated attr() is how to get the custom attributes. However, also note that if you are using HTML5's data-* attributes, you can also now leverage jQuery's .data() to acess that data:
http://api.jquery.com/data/
your implementational problem may be with your use of this. maybe it should be $(this) or you may not be binding correctly. I cannot find any problems with it.. see http://jsfiddle.net/nvkVy/2/
<a href='api.fatherstorm.com' data-ref='test' data:ref='test' data_ref='test' class='testable'>test me</a>
<script>
$(document).ready(function(){
$('.testable').click(function(){
alert('data-ref='+$(this).attr('data-ref'));
alert('data:ref='+$(this).attr('data:ref'));
alert('data_ref='+$(this).attr('data_ref'));
return(false);
});
});
</script>
精彩评论