3

我有这个工作代码,它正在创建一个组合框:

你可以看到它在这里工作:jsfiddle

$('body').on('change', '.combo', function() {
    var selectedValue = $(this).val();

    if ($(this).find('option').size() > 2) {
        var newComboBox = $(this).clone();
        var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10);
        var newComboBoxIndex = thisComboBoxIndex + 1;

        $('.parentCombo' + thisComboBoxIndex).remove();

        if (selectedValue !== '') {
            newComboBox.attr('data-index', newComboBoxIndex);
            newComboBox.attr('id', 'combo' + newComboBoxIndex);
            newComboBox.addClass('parentCombo' + thisComboBoxIndex);
            newComboBox.find('option[val="' + selectedValue + '"]').remove();
            $('body').append(newComboBox);
        }
    }
});

这导致了这样的结果,每次我填充一个组合框时,都会打开下一个。

仅一个组合框

我怎样才能改变那个代码来拥有这个?这意味着打开了两个组合框(请忘记样式

这意味着两个组合框效果

谢谢你。

4

2 回答 2

1

如果您只想将组合框的数量加倍,您可以使用 for 循环并根据计数器变量的值设置它们的值。

于 2012-12-26T18:01:55.407 回答
1

我不完全确定您的意图,但似乎您希望拥有两个select元素的组,然后在用户选择一个值时添加一个新组。

在这种情况下,我建议将您的两个selects 分组为fieldset

<fieldset>
  <select id="combo1" class="combo" data-index="1">
    <option></option>
    <option val="Opt1">Opt1</option>
    <option val="Opt2">Opt2</option>
    <option val="Opt3">Opt3</option>
  </select>
  <select id="combo2" class="combo" data-index="2">
    <option></option>
    <option val="Opt1">Opt1</option>
    <option val="Opt2">Opt2</option>
    <option val="Opt3">Opt3</option>
  </select>
</fieldset>

​然后查找该父fieldset级并像这样克隆它:

$('body').on('change', '.combo', function() {
  var selectedValue = $(this).val();

  var fieldset = $(this).parents('fieldset');

  if ($(this).find('option').size() > 2) {
    var newFieldset = fieldset.clone();
    var newComboBox = $(fieldset).children('.combo:first');
    var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10);
    var newComboBoxIndex = thisComboBoxIndex + 1;

    $('.parentCombo' + thisComboBoxIndex).remove();

    if (selectedValue !== '') {
        newComboBox.attr('data-index', newComboBoxIndex);
        newComboBox.attr('id', 'combo' + newComboBoxIndex);
        newComboBox.addClass('parentCombo' + thisComboBoxIndex);
        newComboBox.find('option[val="' + selectedValue + '"]').remove();
        $('body').append(newFieldset);
    }
  }     
});​

有些细节可能并不完全符合您的需要,但总的来说这是我推荐的方法。

在这里找到更新的小提琴:http: //jsfiddle.net/JaVVe/8/

于 2012-12-26T22:08:26.050 回答