在jquery的帮助下,我已经完成了以下操作,点击一个复选框更改了行的颜色,所有复选框都有相同的类名,代码工作正常,但我们的一个项目中的要求是使用简单的纯JavaScript(无库)
来做到这一点任何人都可以告诉我一些解决方案吗
$(".cbxSelect").click(function (e) {
if (!$(this).closest('tr').hasClass("myclass")) {
$(this).closest('tr').css('background-color', 'yellow');
$(this).closest('tr').addClass("myclass");
} else {
$(this).closest('tr').css('background-color', 'white');
$(this).closest('tr').removeClass("myclass");
}
});
答案 0 :(得分:3)
var boxes = document.querySelectorAll('.cbxSelect');
for (var i=boxes.length; i--;) {
boxes[i].addEventListener('change', handler, false);
}
function handler() {
var el = this;
while (el.parentNode) {
el = el.parentNode;
if (el.tagName.toLowerCase() === 'tr') {
break;
}
}
if (el.getAttribute('data-color') != 'yellow') {
el.style.backgroundColor = 'yellow';
el.setAttribute('data-color', 'yellow');
}else{
el.style.backgroundColor = 'white';
el.setAttribute('data-color', 'white');
}
}
答案 1 :(得分:2)
由于您已经切换myclass
,因此将其用于背景颜色是有意义的:
.myclass {
background: yellow;
}
和JS:
var checks = document.querySelectorAll('.cbxSelect');
for (var i = 0; i < checks.length; i++) {
checks[i].onchange = function() {
var tr = this.parentNode.parentNode;
if (/\bmyclass\b/.test(tr.className)) {
tr.className = tr.className.replace(/\bmyclass\b/g, '');
}
else {
tr.className += ' myclass';
}
};
}