使用jquery添加/删除兄弟元素属性

时间:2012-08-23 14:18:16

标签: jquery

我有这个HTML。

<tr>
    <td width="75">Mon</td>
    <td class="bn_time" width="60">
        <input id="mon_open" name="mon_open" class="time" placeholder="opening time" />
    </td>
    <td class="bn_time" width="10" align="center">-</td>
    <td class="bn_time" width="100">
        <input id="mon_close" name="mon_close" class="time" placeholder="closing time" />
    </td>
    <td colspan="3" align="center" class="bn_holiday" hidden>Holiday</td>
    <td>
        <input type="checkbox" name="mon_closed" id="mon_closed" class="bn_closed" />
        <label for="mon_closed">Closed</label>
    </td>
</tr>

我要做的是将复选事件用于复选框add/remove' hidden attribute to`元素。例如。

if ('#bn_closed').is(':checked') {
    //hide all <td> element with class bn_time
    //show <td> element with class bn_holiday
} else {
    //show all <td> element with class bn_time
    //hide <td> element with class bn_holiday
}

这是我尝试使用jQuery做的。

$('.bn_closed').change(function() {
    var element = $(this);
    var id = element.attr('id');
    var day = id.slice(0,-7);
    var day_open = day+'_open';
    var day_close = day+'_close';
    if(element.is(':checked')) {
        //hide all <td> element with class bn_time
        //show <td> element with class bn_holiday
    } else {
        //show all <td> element with class bn_time
        //hide <td> element with class bn_holiday
    }
});

重要的是要注意,有多个具有相同类名的元素。我想修改兄弟姐妹元素的属性,而不是表格中的所有元素。

谢谢。

1 个答案:

答案 0 :(得分:2)

var checked = element.is(':checked');
var $td = element.closest("td");

$td.siblings(".bn_time").toggle(!checked);
$td.siblings(".bn_holiday").toggle(checked);
相关问题