如果类列表包含多个特定类

问题描述 投票:0回答:5

如果元素

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

if (document.getElementById('recordplayerstick').classList.contains('pinplace pinsongplay')) {
    removepin();
}
javascript class contains
5个回答
29
投票

因为

Element.classList.contains
只接受一个类名,你需要分别检查每个。

你可以使用

Array.prototype.some()
来避免写一堆 or 条件

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

18
投票

如果你要使用 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>


5
投票

使用

...
传播语法

例子

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语法-浏览器兼容性

检查数组中的一项是否存在于另一个数组中


0
投票

不同类型都有一套功能很方便

$.fn.has1Class = function (arrayClasses)
{
    return this.length > 0 ? this[0].has1Class(arrayClasses) : false; 
}

HTMLElement.prototype.has1Class = function (arrayClasses)
{
    if (!this.classList)
        return false;
    if (!Array.isArray(arrayClasses)) {
        throw new Error("The classArray parameter must be an array");
    }
    return [...this.classList].some(cl => arrayClasses.contains(cl));
};

Array.prototype.contains = function (v) {
    for (let i = 0; i < this.length; i++) {
        if (this[i] === v) return true;
    }
    return false;
};

console.log( $('#myInput').has1Class(['c']));
console.log( $('#myInput').has1Class(['a','a','a2']));

let domElem = document.getElementById('myInput');
if(domElem)
    console.log( domElem.has1Class(['a','b','a1']));

https://jsfiddle.net/NickU/7afw5oec/95/


-1
投票

前面的答案中已经说过

.classList.contains()
只能传递一个参数。下面的示例包含一个函数,它将遍历给定的
className
s° 列表并返回
true
如果任何或所有
className
s 被分配给目标 DOM 节点²。

°第三个参数...类
¹ 第二个参数 all
² 第一个参数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>

© www.soinside.com 2019 - 2024. All rights reserved.