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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:03:50  来源:igfitidea点击:

How can I get `data-value` using jQuery?

javascriptjqueryhtml

提问by user3266909

How can I get data-valuecountry 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-valueattribute use below jQuery :

要读取data-valuejQuery 下方的属性使用:

$("#obj-details").data('value');

and to read countryfrom the data-valueuse below jQuery :

countrydata-value下面的 jQuery 使用中读取:

 var value = $("#obj-details").data('value');
 var obj = eval('(' +value + ')');

 var country = obj.country;
 alert(country );

Demo

演示

回答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 objectat data-*attribute utilizing double ""quotation marks.

尝试objectdata-*利用双重属性""引号。

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)

另请参阅如何解析非格式良好的 JSON(可能使用 jQuery)