javascript JQuery:创建一个由我的选择选项的数据属性组成的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13997998/
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-26 20:26:37  来源:igfitidea点击:

JQuery: Create an array made out of the data- attributes of my select options

javascriptjquery

提问by murielg

I have a select multiple with some options. Each option has multiple data- attributes. I would like to create an array that contains each of its data- values. For example my code looks a lot like this:

我有一个带有一些选项的选择多个。每个选项都有多个数据属性。我想创建一个包含每个数据值的数组。例如我的代码看起来很像这样:

<select multiple id='my_select'>
<option data-my_id='1' data-my_parent='3' data-my_name='option1'>My first option</option>
<option data-my_id='2' data-my_parent='3' data-my_name='option2'>My second option</option>
<option data-my_id='3' data-my_parent='3' data-my_name='option3'>My third option</option>
</select>

And the result I am looking for needs to be something like this:

我正在寻找的结果需要是这样的:

[1,3,option1], [2,3,option2], [3,3,option3]

I have researched how to create an array with one of the data- attribute value for each of the options, giving me this [1,2,3], but I have been unsuccessful in coming up with what I need.

我研究了如何为每个选项创建一个具有数据属性值之一的数组,给我这个 [1,2,3],但是我没有成功想出我需要的东西。

Thanks a lot!

非常感谢!

回答by VisioN

var array = $("#my_select > option").map(function() {
    return [$.map($(this).data(), function(v) {
        return v;
    })];
}).get();

DEMO:http://jsfiddle.net/nQ6mE/

演示:http : //jsfiddle.net/nQ6mE/

回答by elclanrs

var arr = [];
$('#my_select option').each(function(){
  var $this = $(this);
  arr.push([ $this.data('my_id'), $this.data('my_parent'), $this.data('my_name') ]);
});