首页 文章

jQuery:无法更改表格单元格的背景颜色

提问于
浏览
0

我花了太多时间解决这个简单的问题,而不是我应该 . 因此,我想看看这个,因为我不明白为什么它不起作用 . 我习惯用jQuery更改CSS属性,但在这种特殊情况下它不起作用 .

所以这是我的功能,应该改变表格单元格的背景颜色:

$("table#project_table td").click(function () {     //function_td
    var currProjectVar = "#MainContent_CurrProject";
    if ($(currProjectVar).val() == "None") {
        $(currProjectVar).val($(this).attr('id'));
        $(this).css("background-color", "red");
    } else {
        $("table#project_table td#" + $(currProjectVar).val()).css("background-color", "blue");
        $(currProjectVar).val($(this).attr('id'));
        $(this).css("background-color", "red");
    }
})

它确实将背景颜色更改为红色,但不更改为蓝色 . 当执行将颜色变为蓝色的那条线时,没有任何反应 . 细胞仍然是红色的 .

这是定义表的代码:

<table id="project_table">
    <tr>
        <td id="0">Project0</td><td id="1">Project1</td><td id="2">Project2</td><td id="3">Project3</td><td id="4">Project4</td><td id="5">Project5</td><td id="6">Project6</td>
    </tr>
    <tr>
        <td id="7">Project7</td><td id="8">Project8</td><td id="9">Project9</td><td id="10">Project10</td><td id="11">Project11</td><td id="12">Project12</td>
    </tr>
</table>

这是我用来存储当前所选项目的隐藏字段:

<input type="hidden" name="ctl00$MainContent$CurrProject" id="MainContent_CurrProject" value="None">

将新单元格标记为红色或更改当前项目的值没有问题 . 我不能让早期的细胞变成蓝色 . 我究竟做错了什么?

顺便说一句:不知道,这是否重要,但这个脚本在ASP.NET网站上运行 .

2 回答

  • 0

    看起来问题是:

    $("table#project_table td#" + $(currProjectVar).val()).css("background-color", "blue");
    

    所以我想方设法a)将这条线分成多条更简单的线条,以及b)获得有关每一步做什么的更多信息 .

    例如,您可以首先在单独的变量中定义ID选择器,然后选择字符串 console.log ,以便您知道它正确生成:

    var target_id = '#' + $(currProjectVar).val();
    // This output will be displayed e.g. in the Chrome developer tools console
    console.log('The target ID to be bluified is: ' + target_id);
    // Your selector can be simplified since a given #ID should be unique for the page.
    $(target_id).css("background-color", "blue");
    

    像这样打破局面是明确问题所在的第一步 .

    另外,请注意我上面的评论;我注意到你并非如此,这可能是你问题的原因;您需要将非唯一ID更改为类 .

  • 0

    不完全确定为什么's not working. I'在jfiddle尝试了你的代码,它似乎做你想要的 .

    但是,我会将代码重写为更高效/可读的内容:

    // variable to store the last clicked project
    var $currentProject;
    // hidden input
    var $currentProjectInput = $("#MainContent_CurrProject");
    
    $("#project_table td").click(function () {
        // set the background of the currently selected project to blue (if any)
        $currentProject && $currentProject.css("background-color", "blue");
    
        // update the current selection to the one we just clicked
        $currentProject = $(this);
    
        // Set the background of the project we just clicked
        $currentProject.css("background-color", "red");
    
        // Set the currently project's id as the hidden input value
        $currentProjectInput.val($currentProject.prop("id"));
    });
    

    见:jsfiddle

相关问题