【问题标题】:How to implement "OR" logic instead of "AND" in jQuery?如何在jQuery中实现“OR”逻辑而不是“AND”?
【发布时间】:2011-12-09 17:17:18
【问题描述】:

我正在尝试修改一个插件,以便它可以在组内使用“OR”逻辑以及在组之间使用“AND”逻辑。这是working example。我的代码如下:

if ($.inArray(tag, itemTags) > -1) {
   return true;
}

如果我在tag 中有["One","Two"],如何为它实现 OR 逻辑。

【问题讨论】:

  • 你能更详细地描述你想要做什么吗?您的问题太简短,无法弄清楚您的要求。请提供插件应该做什么的示例。
  • 我需要在组内实现 OR 并在组间实现“And”
  • @Imran - 我不认为再次重复这个问题可以被认为是“更详细”。
  • @RobW,你不是说ORXORXOR吗? :)
  • 我认为他的意思是应该显示与他的演示小提琴中的任何复选框匹配的任何元素。

标签: javascript jquery filter


【解决方案1】:

我已经 updated your fiddle 拥有我认为是您所追求的功能。

我只是稍微移动了一下逻辑。

【讨论】:

    【解决方案2】:

    如果您的目标浏览器提供array.filter,您可以这样做:

    var matchingTags = itemTags.filter(function(el) { 
                           return $.inArray(el, tag) > -1;
                       });
    

    See it in action.

    【讨论】:

      【解决方案3】:

      使用 ES5 的 .some 方法,这可以相当简洁。旧版浏览器有a shim

      var tag = ["d", "b"],
          tagItems = ["a", "b", "c", "d", "e"];
      
      var contains = tagItems.some(function(v) { // whether at least "d" or "b" is in `tagItems`
          return ~tag.indexOf(v);
      });
      
      if(contains) {
          // ...
      

      tagItems 的行为如下:

      tag = ["d", "b"];        // contains === true (due to "d")
      tag = ["foo", "x", "a"]; // contains === true (due to "a")
      tag = ["bar"];           // contains === false (due to no matches)
      

      您也可以为此创建一个辅助函数:

      $.inArrayMultiple = function(subset, arr) {
          return arr.some(function(v) {
              return ~subset.indexOf(v);
          });
      };
      

      然后你可以使用:

      if($.inArrayMultiple(tag, itemTags)) {
          // ...
      

      【讨论】:

        【解决方案4】:

        一个迂回的解决方案是将您的 inArray 条件包装在一个 $(array).each() 函数中,如果数组中存在任何迭代项,则该函数返回 true。

        var result = function ()
        {
            var r = false;
            $(tag).each(function()
            {
                if ($.inArray(this, itemTags) > -1) 
                {
                   r = true;
                }
            });
            return r;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-09-29
          • 2011-12-26
          • 2010-10-16
          • 2013-12-06
          • 2017-01-11
          • 1970-01-01
          • 2011-05-23
          • 1970-01-01
          相关资源
          最近更新 更多