我想从 javascript 函数返回自定义 json 对象我的代码如下
html
<input type='checkbox' name='chk[]' value='1'>1
<input type='checkbox' name='chk[]' value='2'>2
<input type='text' id='txt' value='' />
<input id='btn' type='button' value='click' />?
Run Code Online (Sandbox Code Playgroud)
js
var json = {};
$('#btn').click(function(){
console.log(getdata());
});
function getdata(){
$('input:checked').each(function(i){
json.chk = $(this).val();
//json.chk.push({"val": $(this).val()}); gives error Uncaught TypeError: Cannot call method 'push' of undefined
});
json.txt = document.getElementById("txt").value;
return json;
}
Run Code Online (Sandbox Code Playgroud)
? 我需要像下面这样的结果
{
chk: [{val: 1}, {val: 2}],
txt: 'test'
};
Run Code Online (Sandbox Code Playgroud)
您需要在 json 对象中定义 chk 变量。由于 chk 未定义,因此它不知道它是一个数组。
\n\nvar json = {};\n\n$(\'#btn\').click(function(){\n console.log(getdata());\n});\nfunction getdata(){\n\n json.chk = [];\n $(\'input:checked\').each(function(i){\n json.chk.push({ val : $(this).val()});\n });\n\n json.txt = document.getElementById("txt").value;\n\n return json;\n}\n\xe2\x80\x8b\nRun Code Online (Sandbox Code Playgroud)\n