【问题标题】:JQuery Sortable, optimize code for multiple input fieldsJQuery Sortable,针对多个输入字段优化代码
【发布时间】:2013-06-11 11:13:50
【问题描述】:

我有 10 个文本输入字段,每个字段都使用 select2 和 jquery 可排序。

实际上,要为每个字段提供可排序功能,我为每个字段都复制了代码,并且效果很好。但正如你所理解的,我会优化它以与 N 个字段一起使用。

我的代码:

    // Sortable
    jQuery("#_posts_1").select2("container").find("ul.select2-choices").sortable({
        containment: "parent", 
        start: function() { jQuery("#_posts_1").select2("onSortStart"); },  
        update: function() { jQuery("#_posts_1").select2("onSortEnd"); } });
    jQuery("#_posts_1").on("change", function() { jQuery("#_posts_1").html(jQuery("#_posts_1").val());});

    [... the same code for each field ...]

    jQuery("#_posts_10").select2("container").find("ul.select2-choices").sortable({
        containment: "parent", 
        start: function() { jQuery("#_posts_10").select2("onSortStart"); }, 
        update: function() { jQuery("#_posts_10").select2("onSortEnd"); } });
    jQuery("#_posts_10").on("change", function() { jQuery("#_posts_10").html(jQuery("#_posts_10").val());});

如何优化独特的功能? 谢谢

【问题讨论】:

  • 为什么不使用类呢?

标签: jquery jquery-ui user-interface jquery-ui-sortable


【解决方案1】:
jQuery("[id^='_posts_'").each(function(i,elem){
        $(elem).select2("container").find("ul.select2-choices").sortable({
        containment: "parent", 
        start: function() { $(elem).select2("onSortStart"); },  
        update: function() { $(elem).select2("onSortEnd"); } });
    $(elem).on("change", function() { $(elem).html($(elem).val());});
});

【讨论】:

  • 虽然您可能也应该重写 .on,但我需要知道帖子容器的名称才能这样做。我可以使用body,但最好不要。
猜你喜欢
  • 1970-01-01
  • 2020-07-10
  • 1970-01-01
  • 2016-02-03
  • 1970-01-01
  • 2011-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多