jQuery get multiple attributes

匿名 (未验证) 提交于 2019-12-03 08:57:35

问题:

I have an element I need to get an array of specific attributes. For example:

<div id="myDiv" class="myClass" data-country="US" data-city="NY" /> 

In this example, I need to get all data-* attributes and place them in array (name and value pairs).

In this example, final array would look like this:

myDataArray["data-country"] = "US"; myDataArray["data-city"] = "NY"; 

Problem is that these attributes are dynamic, I do not know what attributes will be there at the runtime and I cannot hard code filling of array.

回答1:

You can call data() to get all data attributes.

Live Demo

myDataArray = $('#myDiv').data(); alert(myDataArray["country"]); alert(myDataArray["city"]); 

You can iterate through key value pair like this,

Live Demo

arr = $('#myDiv').data();  for(el in arr) {     alert("Key >> " + el);     alert("Value >> " + arr[el]); } 


回答2:

var myDataObject = document.getElementById('myDiv').dataset; 

http://jsfiddle.net/qQWBB/



回答3:

Try this

var data = $('#myDiv').data(); var myDataArray = []; $.each(data, function(key, val){         myDataArray['data-' + key] = val; }); console.log(myDataArray); 

LIVE DEMO



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!