我为我指导的学生创建了以下代码,我想知道是否有人能想到一种更简单的方法或已经存在的方法?我也有兴趣学习如何在 javascript 中创建插件,但忘记了如何/无法在 google 上找到它。
无论如何,这是代码......
window.addEventListener('load', function()
{
for(var i = 0; i < document.forms[0].length; i++)
{
document.forms[0].elements[i].checked = false;
}
}, false);
function formHandler()
{
valArray = new Array();
toppArray = new Array();
var theForm = document.forms[0];
for(var i = 0; i < theForm.length; i++)
{
theValue = theForm.elements[i].value;
if(theForm.elements[i].checked == true)
{
if(theForm.elements[i].type == 'checkbox' && theForm.elements[i].name == 'myChBx')
{
appendArr(toppArray, theForm.elements[i].value);
appendArr(valArray, toppArray, 'topping');
}else
{
appendArr(valArray, theValue);
}
}
}
}
function appendArr(array, value, keyVal = '')
{
if(keyVal != '')
{
array[keyVal] = value;
}else
array[array.length] = value;
}
好的,现在简要解释一下这段代码的作用。在 php 中,我知道你可以使用类似
的方法将一个值附加到数组上$array[] = $value;
但是我读过几个地方如何必须使用对象在 JavaScript 中创建关联数组。在某种程度上,我想我已经做到了,但我使用数组对象成功了。
这样做的目的是从简单的单选和复选框表单中获取值,例如这个......
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="./appendArr.js"></script>
</head>
<body>
<form action="" method="post">
Radio 1:<input type="radio" name="myRdo" id="rdo" value="radio 1" onclick="formHandler();" />
Radio 2:<input type="radio" name="myRdo" id="rdo" value="radio 2" onclick="formHandler();" />
Radio 3:<input type="radio" name="myRdo" id="rdo" value="radio 3" onclick="formHandler();" />
<br />
Checkbox 1:<input type="checkbox" name="myChBx" id="myChBx" value="Checkbox 1" onclick="formHandler();" />
Checkbox 2:<input type="checkbox" name="myChBx" id="myChbx" value="Checkbox 2" onclick="formHandler();" />
Checkbox 3:<input type="checkbox" name="myChBx" id="myChbx" value="Checkbox 3" onclick="formHandler();" />
<br />
<input type="submit" name="submit" id="button" " value="Button" />
</form>
</body>
</html>
并将它们存储在一个数组中,该数组的值之一是一个名为 toppings 的关联数组;因此数组中的某些值将是单个变量,而其他值将是单个变量的集合。
无论如何...我可能只是白白花了一个小时,但我来这里是为了学习,所以请不要恶搞。谢谢
最佳答案
JavaScript 没有关联数组,它有作为索引列表的“数组”,并且有作为键:值容器的“对象”。这似乎与您要问的问题并不相关,所以...您需要回答的实际问题是什么? “如何在 JavaScript 中执行 $arr[] = $val”?如果是这样,那就是push(),如下所示:
["a","b","c"].push("d") // result: ["a","b","c","d"]
如果这不是您的问题,请编辑您的原始帖子,因为完全不清楚您真正想知道什么。
关于javascript - 将值插入关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15302318/