如何在 Dojo 中检查节点是否具有特定的 class?

How to check if a node has particular class in Dojo?

我经常 hide/show 节点到 JavaScript,但现在我需要在显示时设置特定 class inline-block(不是 block)的节点.但是,我对 inline-block class 和其余部分进行排序时遇到问题,class 在这种情况下为空:

show: function (div) {
    if (typeof div === 'object' && typeof div.style === 'object') {
        if (div.class == "inline-block-class") //this doesn't work
        {
            div.style.display = "inline-block";
        } else {
            div.style.display = "block";
        }
    }
}

divdata-dojo-attach-point 引用 - 我可以完全使用 this.someAttachPoint 之类的东西,但是当我将它包装到其他变量中时(例如 div 在我的函数中),我只得到节点的 CSS 选择器——它是一个对象,但我无法在 FireBug.

中得到它的属性

我可以通过添加另一个参数来解决这个问题,一个标志告诉我这个节点应该是 inline-block,但是它很脏并且是另一个出错的机会,所以我更愿意做 block /inline-block函数内部区分。

您可以使用 DOM 元素 divElement.classList 属性,它公开了一个方法 contains

Checks if specified class value exists in class attribute of the element.

if (div.classList.contains("inline-block-class")) 
{
    div.style.display = "inline-block";
} else {
    div.style.display = "block";
}

使用 dojo/dom-class and dojo/dom-style 模块检查 DOM 节点上的 class 并更改样式。

show: function (div) {
if (typeof div === 'object' && typeof div.style === 'object') {
    if (domClass.contains(div, "inline-block-class"))
    {
        domStyle.set(div, 'display', 'inline-block');
    } else {
        domStyle.set(div, 'display', 'block');
    }
}
}

更好的解决方案是使用 CSS 而不是 Javascript 来控制 div.style.display。只需更改 Javascript 中的 classes 并让 CSS 处理样式。