如果我在这里使用正确的语法来检查“aria-expanded”对于具有 css 类“classname”的特定元素集是否为真,请告诉我:
if ($(‘.classname’).hasAttribute('aria-expanded','true')) {
output here
}
最佳答案
jQuery 没有 hasAttribute
方法,因此我假设 $ = docuument.querySelector
。 (注意:不是 document.querySelectorAll
;因此,您只考虑单个元素)。
hasAttribute
方法采用单个参数:您要检查的属性的名称。要检查该属性的值,您需要使用 getAttribute
然后进行比较。所以你可能会这样做:
if( $('.classname').getAttribute('aria-expanded') === 'true') {}
如果您使用的是 jQuery,那么您可以只使用 attr
方法:
if ($('.classname').attr('aria-expanded') === 'true') {}
另请参阅MDN docs for hasAttribute
.
如果您尝试检查一组元素,您可以执行以下操作:
function allHaveAttribute(elements, attrName, attrValue) {
// First, check that all elements have the attribute
for (var i = 0; i < elements.length; i++) {
if (!elements[i].hasAttribute(attrName)) return false;
}
if (attrValue) { // if we're checking their value...
for (var i = 0; i < elements.length; i++) {
if (elements[i].getAttribute(attrName) !== attrValue)
return false;
}
return true;
} else { // we know all elements have the attribute
return true;
}
}
var els = document.querySelectorAll('.classname');
if (allHaveAttribute(els, 'aria-expanded', 'true') {
// action here
}
关于javascript - 如何检查属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37125674/