【问题标题】:If classlist contains more than one specific class如果类列表包含多个特定类
【发布时间】:2019-06-08 23:41:39
【问题描述】:

如果元素 recordplayerstick 包含 pinplacepinsongplay 类,我需要一个函数来触发。我目前拥有的代码返回语法错误。这样做的正确方法是什么?

if (document.getElementById('recordplayerstick').classList.contains('pinplace pinsongplay')) {
    removepin();
}

【问题讨论】:

  • 另外,您一次只能检查一门课程。
  • @Pointy 对如何进行多个课程有什么建议吗? if (document.getElementById('recordplayerstick').classList.contains('pinplace') || document.getElementById('recordplayerstick').classList.contains('pinsongplay')) ?
  • 只需检查它是否包含其中一个(两次调用.contains())。
  • const cl = document.getElementById('recordplayerstick').classList; if (cl.contains('pinplace') || cl.contains('pinsongplay')) ...
  • OP 说 OR 和一堆 cmets 是 AND

标签: javascript class contains


【解决方案1】:

由于Element.classList.contains 只接受一个类名,您需要分别检查。

您可以使用Array.prototype.some() 来避免编写一堆条件

const el = document.getElementById('recordplayerstick')
const classNames = ['pinplace', 'pinsongplay']
if (classNames.some(className => el.classList.contains(className))) {
  removeping()
}

【讨论】:

    【解决方案2】:

    如果要使用 classList,则必须进行两次检查。

    function removepin() {
      console.log("yep");
    }
    var cList = document.getElementById('recordplayerstick').classList;
    if (
      cList.contains('pinplace') ||
      cList.contains('pinsongplay')) {
      removepin();
    }
    <div id="recordplayerstick" class="pinplace pinsongplay"></div>

    【讨论】:

      【解决方案3】:

      使用... (Spread syntax)

      示例

      const element = document.getElementById("left-sidebar");
      const has_some = ["left-sidebar", "js-pinned-left-sidebar"];
      const result = [...element.classList].some(className => has_some.indexOf(className) !== -1);  
      // has_some.some(className => [...element.classList].indexOf(className) !== -1);
      // or example like @Phil
      // has_some.some(className => element.classList.contains(className))
      

      功能齐全

      /**
       * @description determine if an array contains one or more items from another array.
       * @param {array} haystack the array to search.
       * @param {array} arr the array providing items to check for in the haystack.
       * @return {boolean} true|false if haystack contains at least one item from arr.
       */
      var findOne = function (haystack, arr) {
          return arr.some(function (v) {
              return haystack.indexOf(v) !== -1;
          });
      };
      
      /**
       * @description determine if element has one or more className.
       * @param {HTMLElement} element element where is going to search classNames.
       * @param {array} arrayClassNames Array of Strings, provide to search ClassName in the element
       * @return {boolean} true|false if element.classList contains at least one item from arrayClassNames.
       */
      var checkElementHasSomeClassName = function (element, arrayClassNames) {
          // uncoment and use this return if you don't want the findOne function
          // return [...element.classList].some(className => arrayClassNames.indexOf(className) !== -1);
          return findOne([...element.classList], arrayClassNames);
      };
      

      附加链接:

      Spread syntax - browser compatibility

      Check if exist one item from array in another array

      【讨论】:

      • 这似乎不起作用,它只搜索数组中的第一个元素。将类列表改为数组,例如[...element.classlist].includes('a','b', etc)?
      【解决方案4】:

      你可以使用正则表达式:

      let div = document.querySelector("div");
      
      if ( /bubu|moo|bar/i.test(div.className) ) {
        console.log("ok (simple test)");
      }
      
      if ( /default|bar/i.test(div.className) ) {
        console.log("not-ok (partial match of `btn-default`)");
      }
      
      if ( /(?:^|\s)default|bar(?:\s|$)/i.test(div.className) ) {
        console.log("ok (not logging)");
        // ^ - the beginning of line | or \s space character.
        // space char | or $ - line ending
      }
      
      /***/
      
      let names = ["btn", "bar", "bubu"];
      let regex = new RegExp( "(?:^|\\s)" + names.join("|") + "(?:\\s|$)", "i");
      
      if ( regex.test(div.className) ) {
        console.log("ok (new RegExp)");
      }
      <div class="btn btn-default bubu"></div>

      【讨论】:

        【解决方案5】:

        正如前面的答案.classList.contains() 已经说过的,只能传递一个参数。以下示例具有一个函数,它将遍历给定的 classNames° 列表,并在 classNames 中的任何或全部¹分配给目标 DOM 节点²时返回 true

        ° 第三个参数...类
        ¹ 第二个参数全部
        ² 第一个参数DOMNode

        用法

        findClasses(DOMNode, all, ...classes)
        DOMNode.....: The reference to a single DOM element
                      ex. const node = document.querySelector('.target'); 
        all.........: Boolean to determine whether all classes listed in the 
                      third parameter need to be present (true) or just one of
                      them (false)
        ...classes..: ClassNames as a comma delimited list of strings
                      ex. "bullseye", "miss"
        

        示例

        const node = document.querySelector('#recordplayerstick');
        
        const findClasses = (node, all, ...classes) => {
          return all ?
            classes.every(cls => node.classList.contains(cls)) :
            classes.some(cls => node.classList.contains(cls));
        };
        
        // console.log(findClasses(node, false, 'pinplace', 'pinsongplay'));
        // returns true
        
        // console.log(findClasses(node, true, 'pinplace', 'pinsongplay'));
        // returns false
        
        const removePin = () => alert(`PIN REMOVED!`);
        
        if (findClasses(node, false, 'pinplace', 'pinsongplay')) removePin();
        <div id='recordplayerstick' class='pinplace'></div>

        【讨论】:

          猜你喜欢
          • 2015-08-09
          • 2019-07-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-06-16
          • 1970-01-01
          • 2016-08-30
          • 2021-07-26
          相关资源
          最近更新 更多