Javascript Jquery相对下拉列表

Javascript Jquery相对下拉列表,javascript,jquery,html,Javascript,Jquery,Html,代码有2个下拉菜单->类别和子类别。子类别依赖于类别的选择。现在,当我们有3对下拉列表时,问题就出现了。比如,如果我更改第一个下拉列表的类别,它将更改所有3个子类别的下拉列表值 $(文档).on('change','cat_select',函数(e){ $(this).closest().find('.subcat_select').find('option:not(:first')).remove(); $(this).closest().find('.subcat_select').app

代码有2个下拉菜单->类别和子类别。子类别依赖于类别的选择。现在,当我们有3对下拉列表时,问题就出现了。比如,如果我更改第一个下拉列表的类别,它将更改所有3个子类别的下拉列表值

$(文档).on('change','cat_select',函数(e){
$(this).closest().find('.subcat_select').find('option:not(:first')).remove();
$(this).closest().find('.subcat_select').append(data.html);
//html来自一个ajax请求。
});

1.
1.
1.
//结果将在选择cat_select时出现。
1.
1.
1.
//结果将在选择cat_select时出现。
1.
1.
1.
//结果将在选择cat_select时出现。
试试这个

HTML

<div>
  <select class="cat_select" data-parfor="1">
    <option>1</option>
    <option>1</option>
    <option>1</option>
  </select>

  <select class="subcat_select" data-subfor="1">
    // Result will come on selection of cat_select.
  </select>
</div>

<div>
  <select class="cat_select" data-parfor="2">
    <option>1</option>
    <option>2</option>
    <option>3</option>
  </select>

  <select class="subcat_select" data-subfor="2">
    // Result will come on selection of cat_select.
  </select>
</div>

<div>
  <select class="cat_select" data-parfor="3">
    <option>1</option>
    <option>1</option>
    <option>1</option>
  </select>

  <select class="subcat_select" data-subfor="3">
    // Result will come on selection of cat_select.
  </select>
</div>
添加data parfor属性和data subform属性可以使用相同的css类,这意味着样式更少,相反,JS中的选择器使用单击元素属性的值作为目标


您可以在
最近()调用中提供选择器以获取特定的父级。或者,
.parent().parent()
在这种情况下也可以使用

var data={html:“test”}//html来自一个ajax请求。
$(文档).on('change','cat_select',函数(e){
$(this).closest('.row').find('.subcat_select').find('option:not(:first')).remove();
$(this).closest('.row').find('.subcat_select').append(data.html);
});

1.
1.
1.
//结果将在选择cat_select时出现。
1.
1.
1.
//结果将在选择cat_select时出现。
1.
1.
1.
//结果将在选择cat_select时出现。

所有下拉列表都有相同的类,并且在jQuery中使用相同的类。所以我知道,这就是我来这里寻求答案的原因。我同意,这也行。但这里我只有一个div。(2下拉列表)。用户可以根据需要克隆和添加任意多的下拉列表。所以不可能向它们添加数据属性。@JimKasprowicz:这很简单,只需通过“添加属性”中的下拉列表进行枚举即可。在用于添加/克隆的函数中,可以n+1属性号。此方法还允许您更改html的布局/结构,而无需重新处理JS.Cateogry Selectsub Cateogry Select。是这样的。所以我想它不会起作用。@JimKasprowicz有点晚了,但我把它编辑成了你的新HTML结构。
$('.cat_select').on('change', function(e) {     
    var $select = $(this);
    var fornumber = $select.attr('data-parfor');
    $('.subcat_select[data-subfor="'+fornumber+'"]').find('option:not(:first)').remove();
    $('.subcat_select[data-subfor="'+fornumber+'"]').append(data.html);
    //data.html comes from an ajax request.
});