简体   繁体   English

Javascript 迭代多选下拉菜单并将数据推送到 JSON object

[英]Javascript Iterating Over a Multiselect Dropdown and pushing data into a JSON object

I'm trying to work with this javascript code which gets HTML elements by their name and iterate over the array of them and pushing each into a JSON object.我正在尝试使用此 javascript 代码,该代码通过其名称获取 HTML 元素并迭代它们的数组并将每个元素推入 Z0ECD11C1D7A287401D148A23BBD7A2F8B6668CFDE69331CBDBDB6668CFDEZ891AC11 When I run this and print on the console (console.log()) the values array gets populated correctly but the data pushed into JSON is a repetition of one element.当我运行它并在控制台(console.log())上打印时,值数组被正确填充,但推入 JSON 的数据是一个元素的重复。 What I mean is it looks like this;我的意思是它看起来像这样; What am I doing wrong?我究竟做错了什么?

4: {key: "Cars1", value: "march"}
5: {key: "Cars1", value: "march"}



else if (this.name == "cars") {
    var values = $("#carsID").val();
    $.each(values, function (index, value) {
    jsonData["key"] = "Cars";
    jsonData["value"] = value;
    postData.RowInfo.push(jsonData);
});

The problem was that jsonData is declared outside this code block and doesn't get created for each element in the values array.问题是 jsonData 在此代码块之外声明,并且不会为 values 数组中的每个元素创建。

The corrected code;更正后的代码;

else if (this.name == "cars") {
  var values = $("#carsID").val();
  $.each(values, function (index, value) {
  var jsonDataEach = {};
  jsonDataEach["key"] = "Cars";
  jsonDataEach["value"] = value;
                                            
  postData.RowInfo.push(jsonDataEach);                                          
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM