使 SmartTable 的选定行成为自定义颜色

Make SmartTable's Selected Row a Custom Color

选择 table 行后,我想设置自定义突出显示颜色。到目前为止,我已经尝试过但无济于事。我可以使用 javascript 函数识别行,但设置 css 属性不会应用于它们。我可以看出选择是有效的,因为出于某种原因,当我点击一行时,该行的高度会像这样缩小...... 详细信息: smartTable 内部装有一个 mTab​​le。 我的 CSS:

tr.selected{
    background-color:red !important;
}

我的 JS:

onDataReceived:function(){
    var trs = document.querySelectorAll("tr"); //creates array of all tr elements
    for(var i = 0; i < trs.length; i++){
        trs[i].addEventListener("click", function(){this.className += "selected";});
    }
},

SmartTable 的行未绑定并且在收到数据后才显示。在我的函数中,如果行尚未添加到 DOM,我将无法检索 tr 元素的数组。因此,在 XML 中,我的 smartTable 的 dataReceived="onDataReceived".

要将 class 添加到现有的 className 中,可以按照问题中的方式使用 + 完成。但是,在添加新的 class 之前需要有一个 space。所以使用

this.className += " selected";

执行此操作的更好方法(在现代浏览器上,而不是 IE)可能是在 classList 上使用添加功能。这样它只会被添加一次,如果一行被一次又一次地突出显示,它就不会叠加。

this.classList.add(“selected”);

取消选择行后,您可以在 classList 上使用删除功能。

感谢@A Haworth 的指导。

对于那些仍在苦苦挣扎的人,这是我的完整(有效!)代码,当用户点击同一行两次或点击新行时可以取消选择:

onInit:function(){
    var that=this; //'this' refers to the view controller
    this.aTrCounter=[]; //counter is used to ensure only 1 row is selected at a time so only 1row is colored at a time. Reason why this is in onInit is to avoid errors due to pagination
},
onDataReceived:function(){
    var trs = document.querySelectorAll("tr");
    for(var i = 0; i < trs.length; i++){
        trs[i].addEventListener("click", function(){
            if(that.aTrCounter.length===0) { //1st row selection
                this.classList.add("selected"); //'this' no longer refers to view controller, it points to the tr itself 
                that.aTrCounter.push(this); //add tr into array to be counted & for later changes
            }
            else if(that.aTrCounter.length>0){ //2nd row selection
                if(that.aTrCounter[0]===this){ //if user clicks the same row
                    this.classList.remove("selected");
                    that.aTrCounter.pop(); //remove last element from array (in this case, the only element)
                } else if(that.aTrCounter[0]!=this){ //if user clicks different row
                    that.aTrCounter[0].classList.remove("selected");
                    that.aTrCounter.pop();
                    this.classList.add("selected");
                    that.aTrCounter.push(this);
                }
            }
        });
    }
}

如果有更优雅的方案,欢迎提供。