td單擊復選框時,我需要用顏色填充背景。我可以在點擊時管理背景。但不知道如何在未選中的情況下清除它。
td{padding:10px}
<table>
<tr>
<td><input type="checkbox" value="1">1</td>
<td><input type="checkbox" value="2">2</td>
<td><input type="checkbox" value="3">3</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script>
$(function(){
$('td').click(function(event) {
if (!$(event.target).is('input')) {
$('input:checkbox', this).prop('checked', function(i, value) {return !value;});
$(this).css('background-color','#ffcc00');
}
});
});
</script>
uj5u.com熱心網友回復:
我會做這樣的事情來切換背景顏色。比起使用標簽選擇器,我更喜歡class/id選擇器,并且為了表示在JS中使用了class,我在開頭的類名后面附加了“js_”,根據需要更新它。
$(function() {
$(".js_checkbox").on('click', function(e) {
let checkbox = $(this);
let td = $(checkbox).closest("td");
if ($(checkbox).is(":checked")) {
$(td).css("background-color", "#ffcc00")
} else {
$(td).css("background-color", "")
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="checkbox" class="js_checkbox" value="1">1</td>
<td><input type="checkbox" class="js_checkbox" value="2">2</td>
<td><input type="checkbox" class="js_checkbox" value="3">3</td>
</tr>
</table>
uj5u.com熱心網友回復:
可以試試這個;)
<style>td{padding:10px}</style>
<table>
<tr>
<td><input type="checkbox" value="1">1</td>
<td><input type="checkbox" value="2">2</td>
<td><input type="checkbox" value="3">3</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script>
$(function()
{
$('td').click(function(e)
{
// Get input
var input = $(this).find('input:checkbox');
// Toggle checkbox status
if(!$(e.target).is('input')) input.prop('checked', !input.is(':checked'));
// Toggle background-color
$(this).css('background-color', input.is(':checked') ? '#ffcc00' : 'transparent');
});
});
</script>
uj5u.com熱心網友回復:
保持簡單并通過布林值切換背景顏色。不知道為什么你把你的聽眾放在 TD 而不是復選框上。
$(function() {
$('td [type=checkbox]').click(function() {
$(this).closest('td').css('background-color', $(this).prop('checked') ? "#ffcc00" : "#fff");
});
});
td {
padding: 10px
}
<table>
<tr>
<td><label><input type="checkbox" value="1">1</label></td>
<td><label><input type="checkbox" value="2">2</label></td>
<td><label><input type="checkbox" value="3">3</label></td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/406256.html
標籤:
上一篇:如何將水平滾動條添加到引導表?
