jQuery Chained:如何解链链接下拉列表?

时间:2014-09-18 09:19:35

标签: jquery chained

我使用了这个插件: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');,但没有工作。

有什么建议吗?

1 个答案:

答案 0 :(得分: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);
        }
    });
});

Demo.

相关问题