[英]Javascript/JQuery to make Multidimentional Arrary of all DOM Elements i defined?
可以說我在表單上有以下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"
元素的值數組?
因此, Multidimentional 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";
class="post"
的Array
? 不需要一個2維陣列,陣列的索引將指示0
, 1
, 2
,等等。
您可以獲得類似數組的對象,該對象已允許您訪問匹配的元素。
var posts = $('.post');
alert(posts[0].id); // input_1
alert(posts[0].value); // abc
您還可以使用純JavaScript方法getElementsByClassName
來獲取所有元素(盡管jQuery函數必須在不強制使用$()
情況下起作用)
var posts = document.getElementsByClassName('post');
alert(posts[0].id); // input_1
alert(posts[0].value); // abc
替代性地構造一個實際的數組(而不是類似數組的對象),您可以這樣做:
var posts = [];
$('.post').each(function () {
posts.push(this);
});
alert(posts[0].id); // input_1
alert(posts[0].value); // abc
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)
})
將創建多維數組
您可以使用getElementsByClassName()
獲取所有節點,然后將它們映射為所需的格式:
var POST_ELEMENTS = {};
[].forEach.call(
document.getElementsByClassName('post'),
function(item) {
POST_ELEMENTS[item.id] = item.value;
}
);
var obj=[];
console.log(obj);
$('.post').each(function(key,value)
{ obj[key]={};
obj[key][$(value).attr('id')]=$(value).attr('value');
});
這是我的小提琴
我看不到有2個維度的任何原因-據我所知,這里只需要一個:
var posts = {};
$('.port').each(function() {
posts[this.id] = this.value;
});
結果是鍵/值對的對象:
posts = {
'input_1': abc',
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.