简体   繁体   中英

Change colors with javascript

Maybe I was unclear. Say I have three rows, and use the checkbox on row two, then I only want that row to change color, the others shall remain unchanged. Sorry for my poor explanation.

row.insertCell(3).innerHTML = '<input type="checkbox" value="check" onclick="ChangeBackgroundColor(this)">'

function ChangeBackgroundColor(status){
    if (status.checked == true) {
        var x = document.getElementById("myTableData").getElementsByTagName("tr")
        x[1].style.backgroundColor = "green"; 

try to iterate over tags:

function ChangeBackgroundColor(status) {
    if (status.checked == true) {
        var x=document.getElementById("myTableData").getElementsByTagName("tr");
        for (var i=0; i<x.length; ++i) {
            x[i].style.backgroundColor = "green";
        }
    }
}

UPDATE : To get selected row color change using jQuery it will be something like:

$('#myTableData').on('change', 'input[type=checkbox]', function() {
   var self = $(this);
   if (self.is(':checked')) {
      self.closest('tr').css('background-color', 'green');
   }
});

You need to loop through all the elements contained in x and set their colour:

function ChangeBackgroundColor(status){
    if (status.checked) {
        var x = document.getElementById("myTableData").getElementsByTagName("tr");
        for (var i = 1; i < x.length; i++) {
             x[i].style.backgroundColor = "green"; 
        }
    }
}

Or as you tagged jQuery:

row.insertCell(3).innerHTML = '<input type="checkbox" value="check" />'

$('#myTableData').on('change', ':checkbox', function(e) {
    if (this.checked) {
        $('#myTableData tr').css('background-color', 'green');
    }
});

To change only the parent row use this:

function ChangeBackgroundColor(status){
    if (status.checked) {
        status.parentNode.style.backgroundColor = "green";
    }
}

// jQuery alternative:
$('#myTableData').on('change', ':checkbox', function(e) {
    if (this.checked) {
        $(this).closest('tr').css('background-color', 'green');
    }
});

JavaScript doesn't has function to change property of multiple elements once.

I'd go with a for loop.

(function(){
        var c,d;
        HTMLCollection.prototype.LP=NodeList.prototype.LP=Array.prototype.LP=function(a,b){
            d=this.length;
            if(!b)
                for(c=0;d>c;c++)a(c);
            else
                for(c=0;d>c;c++){if(!a(c))break}
            }
}())

Now use querySelectorAll ...

var q=document.querySelectorAll(".class, tagName or #id");
q.LP(function(i){
    q[i].style.backgroundColor="#ffb"
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM