根据选择更改表格的列颜色

时间:2015-07-14 14:53:15

标签: javascript jquery html

我有一个包含3列的表格,并希望将其颜色更改为绿色,具体取决于我在核对清单(表格)中选择的内容。

我想根据我选择的城市更改 GREEN 列。例如,如果我选择纽约,那么纽约专栏将成为绿色。有什么想法吗?

HTML - 表格:

<table id="myTable">
    <tr class="head">
        <th></th>
        <th>New York</th>
        <th>Chicago</th>
        <th>San Francisco</th>
    </tr>
    <tr>
        <th>A Poetic Perspective</th>
        <td>Sat, 4 Feb 2012<br />11am - 2pm</td>
        <td>Sat, 3 Mar 2012<br />11am - 2pm</td>
        <td>Sat, 17 Mar 2012<br />11am - 2pm</td>
    </tr>
    <tr class="even">
        <th>Walt Whitman at War</th>
        <td>Sat, 7 Apr 2012<br />11am - 1pm</td>
        <td>Sat, 5 May 2012<br />11am - 1pm</td>
        <td>Sat, 19 May 2012<br />11am - 1pm</td>
    </tr>
    <tr>
        <th>Found Poems &amp; Outsider Poetry</th>
        <td>Sat, 9 Jun 2012<br />11am - 2pm</td>
        <td>Sat, 7 Jul 2012<br />11am - 2pm</td>
        <td>Sat, 21 Jul 2012<br />11am - 2pm</td>
    </tr>
    <tr class="even">
        <th>Natural Death: An Exploration</th>
        <td>Sat, 4 Aug 2012<br />11am - 4pm</td>
        <td>Sat, 8 Sep 2012<br />11am - 4pm</td>
        <td>Sat, 15 Sep 2012<br />11am - 4pm</td>
    </tr>
</table>

HTML - 表格:

<form name="myForm" method="POST">
    <fieldset>
        <legend>Register your interest</legend>
        <p><label class="title" for="name">Your name:</label>
            <input type="text" name="name" id="name"><br />
            <label class="title" for="email">Your email:</label>
            <input type="text" name="email" id="email"></p>
            <label class="title" for="persons">Persons:</label>
            <input id="personsId" type="text" name="persons" id="persons"></p>
        <p><label for="location" class="title">Your closest center:</label>
            <select class="target" name="location" id="location">
                 <option id="1" value="ny">New York</option>
                 <option id="2" value="il">Chicago</option>
                 <option id="3" value="ca">San Francisco</option>
            </select></p>
        <span class="title">Are you a member?</span>
        <label><input type="radio" name="member" value="yes" /> Yes</label>
        <label><input type="radio" name="member" value="no" /> No</label></p>
    </fieldset>
<div class="submit" id="myButton"><input type="button" value="Register" /></div>
</form>

脚本:

<script type="text/javascript">
    $(document).ready(function(){
        $( ".target" ).change(function() {
            $("tr:even").css("background-color", "green");
        });
    });
</script>

1 个答案:

答案 0 :(得分:0)

而不是使用if else添加data-city属性来映射下拉列表的哪个值对应于表的哪一列。像这样<{1}}添加data-city

th

根据下拉值选择th并获取其索引。根据该索引获取整个列(tds)并更改css。

<th data-city="ny">New York</th>
<th data-city="il">Chicago</th>
<th data-city="ca">San Francisco</th>

这是一个演示 http://jsbin.com/leqinun/1/edit?html,js,output