jQuery-追加到多个下拉列表以将数组键作为类名进行匹配 [英] jQuery - Append to the multiple dropdowns for matching array keys as class name

查看:95
本文介绍了jQuery-追加到多个下拉列表以将数组键作为类名进行匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var obj:

{1: Array(1), 2: Array(1), 5: Array(3), 6: Array(3), 27: Array(2)}
1: ["BC8907"]
2: ["B6789"]
5: (3) ["H67890", "BC567", "BC8907"]
6: (3) ["BH123", "BH1234", "BM2345"]
27: (2) ["EPC123", "EPC1234"]

从上面的数组中可以看到,有五个键(1,2,5,6,27).

As you can see from the above array, there are five keys(1,2,5,6,27).

我在DOM中有一组选择标签,其中任何一个数组键都作为类名.我正在尝试将值添加到所有下拉列表中,作为匹配键的选项(作为类名).

I have a set of select tags in the DOM, with any one of the array key as class name. I'm trying to append values to all the dropdowns as options for the matching key as class names.

例如:

<select name="hno[]" class="5">
    <option value="BC8907" selected="">BC8907</option>
</select>

在上面的下拉菜单中,需要添加键5(H67890,BC567)的值作为下拉菜单,该数字也与类名具有相同的编号.另外,由于下拉列表已经具有相同的值,因此需要忽略BC8907的值.

In the above dropdown, need to append the values of the key 5(H67890,BC567) as the dropdown also having the same number as class name. Also, need to ignore the value BC8907 as the dropdown already has the same value.

预期输出:

<select name="hno[]" class="5">
    <option value="BC8907" selected="">BC8907</option>
    <option>H67890</option>
    <option>BC567</option>
</select>

我每次都尝试使用jquery,但是它没有按预期工作.

I tried with jquery each but it's not working as expected.

注意:数组值和下拉类名称是动态添加的.

Note: The array values and the dropdown class names are dynamically added.

推荐答案

您可以使用 .each 循环遍历您的select,然后获取select的类,然后使用该类获取 JSON对象,然后在其中添加选项.

You can use .each loop to iterate through your select then get class of select and then using that class get JSON Object and then add option inside selects .

演示代码 :

//use json.parse before using..further 
var new_data = {
  "1": ["BC8907"],
  "2": ["BC8907"],
  "5": ["H67890", "BC567", "BC8907"],
  "6": ["BH123", "BH1234", "BM2345"],
  "27": ["EPC123", "EPC1234"]
}
//loop through each selects
$("select").each(function() {
  var classes = $(this).attr("class")
  var option = "";
  var selector = $(this)
  //loop through jsons 
  $(new_data[classes]).each(function(i, val) {
    //if the vlue does not exist
    if (selector.find("option[value=" + val + "]").length == 0) {
      option += '<option value=' + val + '>' + val + '</option>'
    }
  })
  $(this).append(option)
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="hno[]" class="5">
  <option value="BC8907" selected="">BC8907</option>
</select>
<select name="hno[]" class="6">
</select>
<select name="hno[]" class="27">
</select>

这篇关于jQuery-追加到多个下拉列表以将数组键作为类名进行匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆