javascript 使用javascript从锚标签获取自定义数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18961094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get custom data from anchor tag using javascript
提问by null
I'm trying to obtain this value for a javscript function
我正在尝试为 javscript 函数获取此值
<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.
我想获得作为数据值的 id。
I've tried using jquery selectors such as var id = $('a[data-value]').attr();
but obviously have it wrong.
我试过使用 jquery 选择器,var id = $('a[data-value]').attr();
但显然是错误的。
Any help is appreciated.
任何帮助表示赞赏。
回答by adeneo
jQuery's data()
will get the data attribute (but not set it) :
jQuerydata()
将获取数据属性(但不会设置它):
var id = $('#like').data('value');
or plain JS
或普通的 JS
var id = document.getElementById('like').getAttribute('data-value');
回答by Tushar Gupta - curioustushar
回答by Sirko
Plain JavaScript has 2 Variants: getAttribute()and dataset:
纯 JavaScript 有 2 个变体:getAttribute()和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()
:
当您也用 jQuery 标记它时,您可以使用data()
或 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!
使用data()
您只能读取值,而不能更新它!data()
指的是一个 jQuery 数据对象,它只是用data-
HTML 元素的字段初始化,但不更新它们!
回答by Rory McCrossan
You need to use data
to retrieve a data attribute:
您需要使用data
来检索数据属性:
var id = $('a[data-value]').data('value');
Or, given that the a
element has an id
:
或者,假设a
元素有一个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:
您可以使用attr()
,但请注意,这只会获取data
附加到 DOM 元素的属性,因此不被认为是好的做法。使用 jQuery 添加的数据属性只会出现在数据缓存中并且可以通过,data()
因此无法通过这种方式检索:
var id = $('#like').attr('data-value');