javascript - 有人可以帮我 DRY up 这些 jQuery each 循环吗?

标签 javascript jquery dry

function redundantSee() {

  var optionSet1 = $('.wrapper:eq(0)'),
      optionSet2 = $('.wrapper:eq(1)');

  optionSet1.find('.options').each(function(){
      var self = $(this),
          input = self.find('input'),
          title = self.find('.title').text(),
          value = input.val(),
          source = self.find('img').attr('src'),
          id = input.attr('id'),
          listItem = $('<li/>', {'value': value, 'id': id }),
          imageElement = $('<img/>', {'src': source, 'title': title});

      $('div.corresponding1').append(nameListItem);
      listItem.append(imageElement);
  });

  optionSet2.find('.options').each(function(){
      var self = $(this),
          input = self.find('input'),
          title = self.find('.title').text(),
          value = input.val(),
          source = self.find('img').attr('src'),
          id = input.attr('id'),
          listItem = $('<li/>', {'value': value, 'id': id }),
          imageElement = $('<img/>', {'src': source, 'title': title});

      $('div.corresponding2').append(listItem);
      listItem.append(imageElement);
  });
}

为了发布,我已经对此进行了简化,因为将有超过 4 个选项集供此函数循环使用。

我在弄清楚如何将所有重复代码变成更易于管理的代码时遇到了问题。

但是由于每个选项集都有它自己的每个循环,$(this) 变量(以及所有相应的变量)特定于在 ('.options') 元素上运行的循环。

如果我每个循环都做一个并使用一个计数器,就像这样:

$('wrapper').each(function(i){ // ... });

我仍然遇到需要在循环中重新声明特定于该选项集的所有新变量的问题。

谁能帮我弄清楚如何压缩它,这样我就不会在每次向函数添加新选项集时都重复相同的代码?

编辑:每个 $('div.corresponding') 元素都完全不同,因此它们不能用计数器递增。 (例如,一个可能是 $('div.foo') 或 $('div.foo ul.bar')

最佳答案

例如,您可以扩展 jQuery,使其更具可重用性:

// extend jquery
(function($){

    $.fn.redundantSee = function (subSelector) {

        return this.find('.options').each(function () {
            var self = $(this),
            input = self.find('input'),
            title = self.find('.title').text(),
            value = input.val(),
            source = self.find('img').attr('src'),
            id = input.attr('id'),
            listItem = $('<li/>', { 'value': value, 'id': id }),
            imageElement = $('<img/>', { 'src': source, 'title': title });

            $(subSelector).append(listItem);
            listItem.append(imageElement);
        });

    };

}(jQuery));

// and use it like this
$('.wrapper:eq(0)').redundantSee('div.corresponding1');
$('.wrapper:eq(1)').redundantSee('div.corresponding2');

关于javascript - 有人可以帮我 DRY up 这些 jQuery each 循环吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13262533/

相关文章:

javascript - JSON Javascript 解析字符串

javascript - 如何让这个 for...of 循环停止并等待然后再继续? (JavaScript 异步/等待与 Firestore 监听器)

jQuery显示:after when certain DIV is found in document中的内容

javascript - 下拉过滤器

java - 避免 Java 接口(interface)中的样板文件

javascript - 在 iframe 中设置输入文本并提交

javascript - Backbone.js View 中的 $el 和 el 有什么区别?

jquery - 暂停播放按钮

unit-testing - 生产和测试代码常量之间的 DRY

c# - 当我需要为所有表单重载方法时如何保持 DRY?