如何从 Javascript 函数访问在 HTML 隐藏输入中声明的数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25856704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I access an array declared in an HTML hidden input from a Javascript function?
提问by PRASHANT KUMAR
I have declared an array in a hidden input in my HTML form. Now I want to access that array in a Javascript function. For this, I have written the following code:
我在 HTML 表单的隐藏输入中声明了一个数组。现在我想在 Javascript 函数中访问该数组。为此,我编写了以下代码:
<form name="form1">
<input type="hidden" name="sq[]" ></input>
<input type="hidden" name="a" ></input>
</form>
And in the Javascript function:
在 Javascript 函数中:
function myfunction()
{
document.form1.a.value=i; // Here, I can access the variable 'a'
// (since a is not in the form of array)
var i;
for(i=0;i<4;i++)
{
document.form1.sq[i].value=i; // Here, I am not able to access array named sq[].
}
}
回答by FishBasketGordo
Naming a hidden input sq[]
doesn't change it into an array. It's still just a text field essentially. You will need to access the field and parse the value as a comma-separated list (or JSON or whatever format you choose).
命名隐藏输入sq[]
不会将其更改为数组。它本质上仍然只是一个文本字段。您需要访问该字段并将值解析为逗号分隔的列表(或 JSON 或您选择的任何格式)。
Assuming you have a form like so:
假设你有一个这样的表格:
<form name="form1">
<input type="hidden" name="sq[]" value="a,b,c,d" />
<input type="hidden" name="sqjson[]" value='["e","f","g","h"]' />
</form>
You can access the values using split [MDN]:
您可以使用 split [MDN]访问这些值:
var arr = document.form1['sq[]'].value.split(',');
for (var ii = 0; ii < arr.length; ii++) {
console.log(arr[ii]);
}
Or using JSON.parse [MDN], which would make more complex objects easier to store in a hidden field:
或者使用 JSON.parse [MDN],这将使更复杂的对象更容易存储在隐藏字段中:
var arr = JSON.parse(document.form1['sqjson[]'].value);
for (var ii = 0; ii < arr.length; ii++) {
console.log(arr[ii]);
}
回答by Francois
You can store sq
array in JSON format in the hidden field.
您可以sq
在隐藏字段中以 JSON 格式存储数组。
<input type="hidden" name="sq" value="[]" ></input>
Then using JSON.parse
and JSON.stringify
you can deserialize from string value to memory object, add/remove values in the array, then storing it back to the hidden field.
然后使用JSON.parse
,JSON.stringify
您可以将字符串值反序列化为内存对象,添加/删除数组中的值,然后将其存储回隐藏字段。
var $sq = JSON.parse($("#sq").val());
...
$("#sq").val(JSON.stringify($sq);
Without JQuery:
没有 JQuery:
var hf = document.getElementById("sq");
var sq = JSON.parse(hf.value);
...
hf.value = JSON.stringify(sq);
Then you can pass sq
as parameter to functions where needed. Or store it in global variable.
然后您可以sq
在需要时将其作为参数传递给函数。或者将其存储在全局变量中。