【问题标题】:jQuery Chained: How to unchain chained dropdown?jQuery Chained:如何解开链接的下拉列表?
【发布时间】:2014-11-12 13:33:11
【问题描述】:

我用过这个插件: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');,但没有成功。

有什么建议吗?

【问题讨论】:

  • 尝试拨打$('#first').unbind('change');。虽然这会从该下拉列表中取消绑定所有更改事件。
  • 啊,是的。它尝试了$('#second').unbind('change');,如果想回链,只需$('#second').bind('change');
  • 首先,您应该从#first 选择unbind 更改事件,而不是#second。但这仍然行不通,因为chained 插件过滤了来自#second 选择的所有不匹配选项,所以当你“解链”(unbind 来自更改事件)时,#second 选择将有一些选项切断(即永远失去)。只有在取消链接后您将使用全套选项重新初始化 #second select 时,它才能工作。
  • 我用可能的解决方案创建了简单的jsfiddle。它对你有用吗?

标签: jquery chained


【解决方案1】:

Chained 插件过滤来自#second select 的所有不匹配选项,因此当您“取消链接”(从更改事件中取消绑定)时,#second select 将有一些选项被切断(即永远丢失)。

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

$(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.

【讨论】:

  • 啊,你是对的。取消绑定#second 将删除#second 中的选项。你的解决方案对我有用。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-01
  • 2023-04-03
  • 1970-01-01
  • 2010-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多