2014-03-07 38 views
0

什麼是構造構建對象:關的n個元素與[NAME = 「值」]的值對屬性

{ 
type: [ "company", "product", "service" ] 
} 

出的一個簡單的方法:

<input type="radio" name="type" value="company">Company 
<input type="radio" name="type" value="product">Product 
<input type="radio" name="type" value="service">Service 

使用任何庫如jQuery或Underscore.js,或純JavaScript?

一點解釋,因爲它似乎是混亂:

動態構造對象。這意味着,這些HTML元素會產生所示的對象,但如果name屬性是「個人資料」和值是不同的,其結果必然是:

{ 
profile: [ "profile1", "profile2", "profile3" ] 
} 
+0

你可以使用更多的話來解釋什麼是你想怎麼辦? –

回答

1

這應該這樣做很容易使用

function getInputValues(name) 
{ 
    return $('input[name="' + name + '"]').map(function() { 
     return this.value; 
    }).get(); 
} 

var data = { 
    type: getInputValues('type') 
}; 

隨着本地JavaScript:

function getInputValues(name) 
{ 
    return [].map.call(document.getElementsByName(name), function(item) { 
     return item.value; 
    }); 
} 

雖然,這是假定你通過名稱始終是<input>元素;如果這是一個問題,您應該使用查詢選擇器。

Demo

0

這裏有一個非jQuery的解決方案

var inputs = querySelectorAll("input[name=type]"); 

var obj = {}; 

obj.type = [].map.call(inputs, function(elem) { 
    return elem.value; 
}); 
相關問題