【问题标题】:Jquery multiselect - Togggle hide optgroup issuesJquery 多选 - 切换隐藏 optgroup 问题
【发布时间】:2015-02-17 14:46:52
【问题描述】:

我已经实现了jquery multiselect addon 并让它正常工作。我有一长串选择选项,并按 optgroups 划分。虽然 optgroups 组织了我的长列表,但用户仍然需要滚动一段时间才能到达底部选项。我只是在寻找一种解决方案,让 optgroup 在默认情况下折叠并在您单击组时不折叠。

当您单击 optgroup 时,它会自动选择它下面的所有我想阻止的选项,而是用隐藏功能替换它。我知道默认情况下 jquery 不能以选择的 optgroup 为目标,但 Jquery Multiple select 插件有一个显然也允许您的事件处理程序。如果您向下滚动一点their site,它会为您提供此插件支持的所有事件处理程序。我对optgrouptoggle 事件非常感兴趣:

当点击 optgroup 标签时触发。此事件接收原始事件对象作为第一个参数,并接收值的哈希作为第二个参数:js $("#multiselect").bind("multiselectoptgrouptoggle", function(event, ui){ /* event: the original event object, most likely "click" ui.inputs: an array of the checkboxes (DOM elements) inside the optgroup ui.label: the text of the optgroup ui.checked: whether or not the checkboxes were checked or unchecked in the toggle (boolean) */ });

我尝试如下实现一个显示隐藏功能,但我还是 jquery 的新手,可能完全搞砸了。任何帮助将不胜感激。

http://jsfiddle.net/akhyp/1986/

$("#selected_items").bind("multiselectoptgrouptoggle", function(event, ui){ 
    $(this).children().show();
}, function() {
    $(this).children().hide();
 });

【问题讨论】:

    标签: javascript php jquery html jquery-multiselect


    【解决方案1】:

    这种方法存在一些问题,一些在您的代码中,一些在插件的 API 中:

    1. 您的演示代码引用了$("#selected_items"),它不在您的标记中。将选择器更改为 $("select") 以匹配您在上面对 multiselect 的声明。更好的是,将 jQuery 对象缓存在一个变量中:var $multiselect = $('select');

    2. 文档指定使用bind 附加事件侦听器,但在最近的jQuery 版本中不推荐使用bind。请改用on

    3. 您将两个函数传递给on/bind 方法——它只需要一个。不用hide()show(),你可以直接用jQuery's toggle method

    4. multiselect 插件没有在语义上构建其生成的标记,因此 optgroups 及其子 option 元素被直接转换为 li 元素,optgroupoption 元素为兄弟姐妹。这意味着您不能以您希望的方式使用children()。但是,API 为您提供了一种方法来查找与optgroup 关联的复选框:ui.inputs。从中,您可以找到每个父 li 元素并隐藏它们。不幸的是,API 似乎没有为您提供直接解决它们的方法,但您可以使用如下代码 sn-p:

      var parentLiOfInput = function(input) { return $(input).closest('li'); }; var $listEls = ui.inputs.map(parentLiOfInput); // $listEls is now an array of jQuery objects // Note this isn't the same as a jQuery wrapped set-- // you can't do $listEls.hide(), for example.

    5. 隐藏生成的“选项”元素将阻止插件工作——它使用 jQuery 选择器来切换复选框,并且该选择器依赖于关联的元素才能显示。

    最后一点是阻止程序:隐藏复选框后,插件将在下一次 optgroup 单击时失败。 Demo of the failing behavior.

    如果不直接修改插件的代码,我目前还没有看到任何适合您的选项。

    【讨论】:

    • 非常感谢对此的详细回复。我将继续挖掘解决这个问题的一些工作,如果这变得太复杂,我可能会寻找一个不同的 Jquery mulitselect 插件并从那里开始工作。
    • 谢谢。如果您发现该回复有用,请随意投票而不接受它,以向该网站的未来用户表明该答案对您的问题有所帮助。祝您搜索顺利。
    • 在深入研究了这个插件的文档后,我发现我可以使用以下代码:$(function () { $("#selected_items").multiselect({ optGroupCollapsible: true }); }); 但这也需要我使用插件的更新版本。我找不到找到这些详细信息的链接,但如果我发现有问题,请务必一起分享。
    • 给你github.com/ehynds/jquery-ui-multiselect-widget。如果你下载了整个包,那里有一些演示页面,你可以试试,还有一个叫做 optgroup,你可以在这里看到 HTML 页面github.com/aerichmond/jquery-ui-multiselect-widget/blob/master/…。我唯一需要弄清楚的是如何在加载页面时使其处于折叠状态,而不是在加载时扩展所有内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    • 2011-01-10
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    相关资源
    最近更新 更多