最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - get custom data from anchor tag using javascript - Stack Overflow

programmeradmin4浏览0评论

I'm trying to obtain this value for a javscript function

<a href="#" id="like" name="like" data-value="<?php echo $_GET['id'];?> " onclick="like(); return false;">
                <img src="<?php echo $ROOT. "/assets/images/templates/like.png"?>" class="aligncenter" alt="" /></a>

I'd like to get the id which is the data-value.

I've tried using jquery selectors such as var id = $('a[data-value]').attr();but obviously have it wrong.

Any help is appreciated.

I'm trying to obtain this value for a javscript function

<a href="#" id="like" name="like" data-value="<?php echo $_GET['id'];?> " onclick="like(); return false;">
                <img src="<?php echo $ROOT. "/assets/images/templates/like.png"?>" class="aligncenter" alt="" /></a>

I'd like to get the id which is the data-value.

I've tried using jquery selectors such as var id = $('a[data-value]').attr();but obviously have it wrong.

Any help is appreciated.

Share Improve this question asked Sep 23, 2013 at 13:53 nullnull 3,5177 gold badges48 silver badges93 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

Plain JavaScript has 2 Variants: getAttribute() and dataset:

var el = document.getElementById( 'like' );
el.getAttribute( 'data-value' ); 
el.dataset.value;

As you tagged this with jQuery as well, you could use data() or attr():

$( '#like' ).data( 'value' );
$( '#like' ).attr( 'data-value' );

Using data() you can only read the value, but not update it! data() refers to a jQuery data object, which is just initialized with data- fields of the HTML element, but does not update them!

jQuery's data() will get the data attribute (but not set it) :

var id = $('#like').data('value');

or plain JS

var id = document.getElementById('like').getAttribute('data-value');

use .data()

var id= $('#like').data('value');

.data() Store arbitrary data associated with the matched elements

You need to use data to retrieve a data attribute:

var id = $('a[data-value]').data('value');

Or, given that the a element has an id:

var id = $('#like').data('value');

You can use attr(), but note this will only get data attributes which are attached to the DOM element and as such is not considered good practice. Data attributes added using jQuery will only appear in the data cache and available through data() so cannot be retrieved in this way:

var id = $('#like').attr('data-value');
发布评论

评论列表(0)

  1. 暂无评论