1

可以说DOM我的表格上有以下内容:

<body>
    <input id="input_1" class="post" type="text" value="abc" />
    <input id="input_2" class="xxxx" type="text" value="xyz" /> <!--TO IGNORE-->
    <input id="input_3" class="post" type="checkbox" checked="checked" />
    <input id="input_4" class="post" type="radio" checked="checked" />
    <select id="input_5" class="post">
        <option value="1">One</option>
        <option value="2" selected="selected">Two</option>
    </select>
    <input id="input_6" class="xxxx" type="checkbox" /> <!--TO IGNORE-->
</body>

如何获得所有class="post"元素的值数组?
所以 anMultidimentional Array将是这样的方式:

POST_ELEMENTS[0]["input_1"] = "abc";
POST_ELEMENTS[1]["input_3"] = 1;
POST_ELEMENTS[2]["input_4"] = 1;
POST_ELEMENTS[3]["input_5"] = "two";
  • 请问如何构建这种Array属于所有特定类的?class="post"
4

5 回答 5

2

You don't need a 2 dimension array, the index of an array will indicate 0, 1, 2, etc.

Array-like jQuery object

You can get an array-like object which allows you to access matching elements already.

var posts = $('.post');

alert(posts[0].id); // input_1
alert(posts[0].value); // abc

Array-like pure JS lookup

You can also use the pure JavaScript method getElementsByClassName to grab all the elements (though jQuery functions won't work without casting $())

var posts = document.getElementsByClassName('post');

alert(posts[0].id); // input_1
alert(posts[0].value); // abc

Array

Alernatively to construct an actual array (not an array-like object) you can do this:

var posts = [];
$('.post').each(function () {
    posts.push(this);
});

alert(posts[0].id); // input_1
alert(posts[0].value); // abc
于 2013-04-05T08:32:39.340 回答
1

您可以获取所有节点,getElementsByClassName()然后将它们映射为您想要的格式:

var POST_ELEMENTS = {};
[].forEach.call(
    document.getElementsByClassName('post'), 
    function(item) {
        POST_ELEMENTS[item.id] = item.value;
    }
);

演示

于 2013-04-05T08:39:42.373 回答
1
var posts = {}

$('.post').each(function(v,i){
    posts[this.id] = this.value
})

将返回一维数组 { 'input_1': 1, 'input_2' : 2 }

var posts = []

$('.post').each(function(v,i){
    var obj = {}
    obj[this.id] = this.value
    posts.push( obj)
})

将创建多维数组

于 2013-04-05T08:30:59.700 回答
1
var obj=[];
  console.log(obj);
$('.post').each(function(key,value)
                {  obj[key]={};
                obj[key][$(value).attr('id')]=$(value).attr('value');               

              });

这是我的小提琴

于 2013-04-05T09:00:51.590 回答
0

I don't see any reason for there being 2 dimensions - you only need one here as far as I can see:

var posts = {};
$('.port').each(function() {
    posts[this.id] = this.value;
});

with the result being an object of key/value pairs:

posts = {
    'input_1': abc',
    ...
}
于 2013-04-05T08:32:28.297 回答