1

我使用了这个插件:https ://github.com/tuupola/jquery_chained

我已经链接了下拉列表,在某些情况下,我想根据事件取消链接并重新绑定链接。

这里有一些例子:

<select id="first">
<option value="a">A</option>
<option value="b">B</option>
</select>

<select id="second">
<option value="c" class="a">C</option>
<option value="d" class="a">D</option>
<option value="e" class="b">E</option>
</select>

<input type="checkbox" value="1" id="unchain" />

Javascript 将是:

$('#second').chained('#first');
$('#unchain').change(function(){
  if ($(this).prop('checked'))
  {
    // how to unchain the chained dropdown?
  }
});

试过$('#second').unbind('chained');但没有用。

有什么建议吗?

4

1 回答 1

2

链式插件从#second选择中过滤所有不匹配的选项,因此当您“解链”(从更改事件解除绑定)时,#second选择将切断一些选项(即永远丢失)。

#second只有在取消链接后您将使用全套选项重新初始化选择时,它才能工作。所以应该做这样的事情:

$(function () {
    // remember #second select
    var secondCopy = $('#second').clone();
    $('#second').chained('#first');
    $('#unchain').change(function(){
        if ($(this).prop('checked')){
            $('#second').chained('#first');
        }
        else{
            $('#first').unbind('change');
            // remember selected value:
            var value = $('#second').val();
            // populate #second select with remembered options
            $('#second').html(secondCopy.html());
            // set saved value
            $('#second').val(value);
        }
    });
});

演示。

于 2014-09-18T12:01:14.280 回答