jQuery获得多个属性 [英] jQuery get multiple attributes
本文介绍了jQuery获得多个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个需要获取特定属性数组的元素. 例如:
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" />
在此示例中,我需要获取所有data-*
属性并将它们放置在数组(名称和值对)中.
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.
推荐答案
您可以调用 data () 获取所有数据属性.
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]);
}
这篇关于jQuery获得多个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文