【问题标题】:Can this jQuery list filtering be done better?这个 jQuery 列表过滤可以做得更好吗?
【发布时间】:2014-05-13 02:21:15
【问题描述】:

我有一个网页,其中包含一个项目列表,每个项目都可以有标签。我想按标签过滤它们,使用逻辑 AND 对它们进行排序:要可见,项目必须具有所有选定的标签。

但我也有一个特殊的“null”排序属性。如果它被选中,那么没有标签的元素无论如何都必须保持可见。

我已经实现了它,但出于好奇,我尝试做得更好,但没有成功。这可以仅在一个条件下完成吗?或者这已经是最好的了?

var activeTags = getAllCurrentlyActiveTags();
$('#list>li').show();
$.each(activeTags, function(index, tag) {
  $('#list>li').each(function() {
    var myTags, keepForNull, notJustNull, currentFailCheck;
    // Array of tags for the current item.
    myTags = getMyTags(this);

    keepForNull = activeTags.indexOf('null') !== -1 && myTags.length === 0;
    notJustNull = tag === 'null' && !(activeTags.length === 1 && activeTags[0] === 'null');
    currentFailCheck = myTags.indexOf(tag) === -1;

    if (keepForNull) {
      return;
    }
    if (notJustNull) {
      return;
    }
    if (currentFailCheck) {
      $(this).hide();
    }
  });
});

有没有更好的方法来做到这一点?

【问题讨论】:

  • 如果您交换循环(即循环遍历每个项目,并在每个标签内循环),那么您可以在内循环之外执行keepForNull 逻辑,因为它不依赖于当前标签.
  • 看起来你有一堆应该声明的局部变量,所以它们不是隐式全局变量。
  • @sje397 - keepForNull,取决于在内部循环中确定的myTags.length。我不认为它可以移出内部循环。
  • @jfriend00 你是对的。它们被重命名了,我忘了在声明中重命名它们。我现在就这样做。谢谢。
  • @sje397 第一个布尔值检查当前项目是否没有标签,因此应该保持显示。所以它确实取决于当前标签和当前项目。

标签: jquery if-statement optimization logic


【解决方案1】:

作为一个小改进怎么样?

var activeTags = getAllCurrentlyActiveTags();   
//// no need to search the active tags array for 'null' repeatedly 
var hasNull = activeTags.indexOf('null') !== -1;
//// only fetch the list items from the DOM once
$('#list>li').each(function() {
  //// keep a flag so we don't hide and/or show the same item more than once
  var show = true;

  //// only fetch tags for each list item once
  // Array of tags for the current item.
  var myTags = getMyTags(this);

  //// if we're keeping it, skip the loop over tags
  var keepForNull = hasNull && myTags.length === 0;      
  if (!keepForNull) {      
    //// use a for loop so the the early 'break' is clear
    for(var index = 0; index < activeTags.length; index++) {
      var tag = activeTags[index];

      //// simplified but equivalent condition
      var notJustNull = tag === 'null' && activeTags.length !== 1;
      if (notJustNull) {
        continue;
      }

      //// only search myTags array when all other checks pass
      var currentFailCheck = myTags.indexOf(tag) === -1;    
      if (currentFailCheck) {
        show = false;
        //// don't need to look at any more tags
        break;
      }
    }
  }

  //// only show/hide once as appropriate
  show ? $(this).show() : $(this).hide();
});

如果您可以修改更广泛的逻辑,您可能会进一步改进它,因为当用户激活(非空)标签或取消激活空标签时,您只需要查看可见项目即可工作找出要隐藏的。反之亦然。

(OT:我确实认为最好将 var 与变量放在一起 - 这样可以更容易地扫描意外的全局变量。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 2016-10-24
    相关资源
    最近更新 更多