javascript 如何使用 jQuery 获取“数据值”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24570256/
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
How can I get `data-value` using jQuery?
提问by user3266909
How can I get data-value
country using jQuery? I need this in variable:
如何data-value
使用 jQuery获取国家/地区?我需要这个变量:
var country = ...;
HTML:
HTML:
<a id="obj-details" data-value="{city:'berlin', street: 'mozart', postal_code: '55555', country: 'DE'}">test</a>
采纳答案by Bhushan Kawadkar
To read data-value
attribute use below jQuery :
要读取data-value
jQuery 下方的属性使用:
$("#obj-details").data('value');
and to read country
from the data-value
use below jQuery :
并country
从data-value
下面的 jQuery 使用中读取:
var value = $("#obj-details").data('value');
var obj = eval('(' +value + ')');
var country = obj.country;
alert(country );
回答by Arunkumar
Use:
利用:
$("#obj-details").attr('data-value');
回答by Jaison
If you looking the return data as a object, try like below.
如果您将返回数据视为对象,请尝试如下操作。
var country = eval('(' + $("#obj-details").attr('data-value') + ')');
alert(country.city);
回答by Cattla
$('#obj-details').data('value');
回答by Rajaprabhu Aravindasamy
Try to use .data(key)
to retrieve that value,
尝试使用.data(key)
检索该值,
var obj = JSON.parse($("#obj-details").data('value')); //Entire object
var country = obj.country; //Country value
回答by minam.cho
jquery.parseJSON(jquery("#obj-details").attr("data-value"));
jquery.parseJSON(jquery("#obj-details").attr("data-value"));
回答by guest271314
Try object
at data-*
attribute utilizing double ""
quotation marks.
尝试object
在data-*
利用双重属性""
引号。
html
html
<a id="obj-details"
data-value='{"city":"berlin"
, "street": "mozart"
, "postal_code": "55555"
, "country": "DE"
}'>test</a>
js
js
var obj = JSON.parse($("#obj-details")[0].dataset.value);
var country = obj.country;
$("#obj-details").text(country);
jsfiddle http://jsfiddle.net/guest271314/6LcfS/
jsfiddle http://jsfiddle.net/guest271314/6LcfS/
See also How can you parse NON wellformed JSON (maybe using jQuery)