考虑一个html表单,其中包含一些表单元素,如标签,选择框单选按钮等。在javascript的帮助下,我想将该表单的子元素存储在json字符串中,如下所示:
{
"label": {
"content": "This is a label"
},
"textbox",
},
"checkbox": {
"option": "Option 1",
"option": "Option 2",
"option": "Option 3"
},
"select": {
"option": "Option 1",
"option": "Option 2"
}
你知道如何实现这个目标吗?有没有我可以获得灵感的代码示例?
答案 0 :(得分:0)
你可以这样做:
List<SomeItem> someItems = getSomeItems();//Receive items for adapter from some place
MyRecyclerAdapter adapter = new MyRecyclerAdapter(someItems);
adapter.setOnItemClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = orderListView.getChildAdapterPosition(v);
SomeItem item = someItems.get(position);
Log.v("CLICKED", "Clicking on item(" + position + ", " + item + ")");
}
});
adapter.setDeleteButtonListener(new OnDeleteButtonItemClickListener {
@Override
public void onDeleteIsClick(View button, int position) {
SomeItem item = someItems.get(position);
Log.v("CLICKED", "Clicking on delete button of item(" + position + ", " + item + ")");
}
});
recyclerView.setAdapter(adapter);
HTML:
function setAllElements() {
var inputElements = document.getElementsByTagName('input');
var selectElements = document.getElementsByTagName('select');
var jsonObj = {};
//Handling of all inputs
for (i = 0; i < inputElements.length; i++) {
if (inputElements[i].type == "text")
jsonObj[inputElements[i].type+i] = inputElements[i].value;
}
//Handling of all select
for (i = 0; i < selectElements.length; i++) {
jsonObj[selectElements[i].type+i] = selectElements[i].value;
}
console.log(jsonObj);
}
如果你想要JSON对象,那么键不能相同,所以我已经把这个元素的数量放在一样,如果你有5个<input type="text" value="Text first">
<select id="e">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<select>
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<input type="button" onclick="setAllElements();" value="Click me!!">
那么它会给你text0,text1,text2,text3,text4及其相应的值。
input type="text"
同样,您可以通过添加对页面中使用的所有元素(如textarea,按钮等)的支持来扩展此功能。
希望它对你有帮助!!