我有一个html页面,它是这样制作的:
<table id="all">
<tr><td><input type="text" name="search[id]" id="search[id]"></input></td></tr>
<tr><td><input type="text" name="search[name]" id="search[name]"></input></td></tr>
..........ecc ecc..........
</table>我想用javascript或jquery实现一个这样的数组:
{
id:"<value in search[id]>",
name:"<value in search[name]>",
....ecc ecc...
}数组的键不是静态的,所以我不能在代码中静态地命名它们。我尝试了$("#search"),但我一直不太幸运:(非常感谢你的帮助!对于这个菜鸟问题,我很抱歉!
发布于 2013-03-05 01:14:46
jQuery提供了$(form).serializeArray() as documented on their API site (它总是值得一看)。
发布于 2013-03-05 01:10:23
var obj = {};
$('#all [id^=search]').each(function() {
obj[this.id.match(/\[(.*)\]/)[1]] = this.value;
});DEMONSTRATION
发布于 2013-03-05 02:36:29
这在本地JavaScript中是可行的;假设您的
function nameToObj(queryName, nodes, context) { // `nodes`, `context` optional
var o = {}, i, j = queryName.length; // var what we'll need
context || (context = document);
// if `context` falsy, use `document`
nodes || (nodes = context.getElementsByTagName('input'));
// if `nodes` falsy, get all <input>s from `context`
i = nodes.length; // initial `i`
while (i--) { // loop over each node
if (nodes[i].name.slice(0,j) === queryName) { // test
o[nodes[i].name.slice(j+1,-1)] = nodes[i].value;
// match, append to object
}
}
return o; // return object
}
nameToObj('search'); // Object {name: "", id: ""}https://stackoverflow.com/questions/15206966
复制相似问题