我是JavaScript的新手,我认为在这一点上,我可能会比我咀嚼更多。本质上,我正在尝试创建一个字典(最终将序列化为JSON,如果这是相关的),它允许用户定义任意数量的条目并根据需要设置键和值。我想要另外一个实现想法,但到目前为止我已经尝试解决它了。
我有一个调用以下代码的按钮,它完全模仿newVariableDescription类。这将在Web表单上创建文本输入框。
var nameElement = document.createElement("input");
nameElement.type = "text";
nameElement.className = "newVariableName";
var nameDiv = document.createElement("div");
nameDiv.type = "div";
nameDiv.appendChild(nameElement);
var newVariableNamesDiv = document.getElementById("newVariableNamesDiv");
newVariableNamesDiv.appendChild(nameDiv);
var descriptionElement = document.createElement("input");
descriptionElement.type = "text";
descriptionElement.className = "newVariableDescription";
var descriptionDiv = document.createElement("div");
descriptionDiv.type = "div";
descriptionDiv.appendChild(descriptionElement);
var newVariableDescriptionsDiv = document.getElementById("newVariableDescriptionsDiv");
newVariableDescriptionsDiv.appendChild(descriptionDiv);
现在,这部分有效。我将所有文本框显示出来,就像我想要的那样,并可以输入它们。但是,我无法弄清楚如何动态访问此列表并将它们配对在一起。
这个帖子与我想做的非常相似:dynamic dictionary using javascript
但我无法弄清楚如何让这段代码做我想做的事情:
var dictionary = {};
$('.newVariableName).each(function (index) {
dictionary['['+index+'].Key'] = $(this).val();
dictionary['['+index+'].Value'] = //access corresponding newVariableDescription here
});
我显然可以使用另一个类(newVariableDescription)创建第二个循环,但这不会将它们正确地绑定在一起。我可以将它们存储在各自独立的列表中,然后将这两个列表组合成一个字典,但我担心订单保持一致,这不是一个优雅的解决方案。
提前感谢您的帮助。
答案 0 :(得分:1)
如果我理解得对,你需要:eq选择器
这样的东西var dictionary = {};
$('.newVariableName').each(function (index) {
dictionary['['+index+'].Key'] = $(this).val();
dictionary['['+index+'].Value'] = $('.newVariableDescription:eq('+index+')').val();
});