简体   繁体   中英

Added class using javascript not working

I am adding two classes using javascript on my table, the css for the classes is:

//using less
.fade-table {
    background-color: #fff;
    opacity: 0.5;
    &:hover {
        opacity: 1;
    }
}

.selected {
    opacity: 1;
}

what i am trying to achieve here is that, my table fades at the opacity: 0.5 and the selected cell is applied with the selected class which highlights the selected cell.

The javascript being used is:

$("#pending_states table tr").live("click",function(){
    $("#pending_states table").css({width: "140px"});
    $("#pending_states td:nth-child(1), #pending_states th:nth-child(1)").addClass("fade-table");
    $("#pending_states td:nth-child(1), #pending_states th:nth-child(1)").css({width: "140px"});
    $("#pending_states").animate({ marginLeft: "4px"}, 200);
    $(this).addClass("selected");
});

However for some reason after adding the fade-table class the script doesn't apply the selected class to the td . The obvious reason that i can think of is that this doesn't represent the td so o also tried $(this).closest("td").addClass("selected"); . However this doesn't seem to work either.

Any suggestions on how this might work?

If you want to apply "selected" to the <td> that was clicked on, try:

 $("#pending_states table tr").live("click",function(e){
    $("#pending_states table").css({width: "140px"});
    $("#pending_states td:nth-child(1), #pending_states th:nth-child(1)").addClass("fade-table");
    $("#pending_states td:nth-child(1), #pending_states th:nth-child(1)").css({width: "140px"});
    $("#pending_states").animate({ marginLeft: "4px"}, 200);
    ($(e.target).is('td') ? $(e.target) : $(e.target).closest('td')).addClass("selected");
 });

(or something less ugly). The idea is to use the event parameter to find the actual target of the click.

You are setting opacity on the wrong element. fade-table is applied to the cell, but selected is applied to the row, so the cell will still be set at 50% opacity.

http://jsfiddle.net/UNgbh/2/

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