我正在尝试获取我单击的特定复选框的数据,如果我取消选中它但单击全部,则该数据消失我希望显示表格的所有数据。
不想用JQuery,想用JavaScript。我尝试按照下面的代码进行操作,但无法达到我期望的结果。
function myFunction() {
var checkBox = document.getElementsByClassName("All")[0];
var text = document.getElementsByClassName("text")[0];
if (checkBox.checked == true) {
text.style.display = "block";
} else {
text.style.display = "none";
}
}
function firstFunction() {
var checkBox = document.getElementsByClassName("select-one")[0];
var text = document.getElementsByClassName("text-one")[0];
if (checkBox.checked == true) {
text.style.display = "block";
} else {
text.style.display = "none";
}
}
function secondFunction() {
var checkBox = document.getElementsByClassName("select-two")[0];
var text = document.getElementsByClassName("text-two")[0];
if (checkBox.checked == true) {
text.style.display = "block";
} else {
text.style.display = "none";
}
}
<input type="checkbox" class="All" onclick="myFunction()">All
<input type="checkbox" class="select-one" onclick="firstFunction()">Select 1
<input type="checkbox" class="select-two" onclick="secondFunction()">Select 2
<table class="text" style="display:none">
<tr>
<td>Checkbox is CHECKED!</td>
</tr>
<tr>
<td class="text-one" style="display:none">Checkbox is CHECKED 1!</td>
</tr>
<tr>
<td class="text-two" style="display:none">Checkbox is CHECKED 2!</td>
</tr>
</table>
我希望我的输出在单击“全部”时显示所有值,而在单击特定复选框时仅显示特定值。
最佳答案
您可以尝试以下方式:
function myFunction(chk) {
var all = document.querySelectorAll('.text tr td');
if(chk.classList.value.includes('All')){
if(chk.checked){
all.forEach(function(td){
td.style.display = "block";
});
}
else{
all.forEach(function(td){
td.style.display = "none";
});
}
}
if(chk.classList.value.includes('select-one')){
document.querySelector('.All').checked = false;
all.forEach(function(td){
td.style.display = "none";
});
if(chk.checked){
document.querySelector('.text-one').style.display = "block";
}
if(document.querySelector('.select-two').checked){
document.querySelector('.text-two').style.display = "block";
}
}
if(chk.classList.value.includes('select-two')){
document.querySelector('.All').checked = false;
all.forEach(function(td){
td.style.display = "none";
});
if(chk.checked){
document.querySelector('.text-two').style.display = "block";
}
if(document.querySelector('.select-one').checked){
document.querySelector('.text-one').style.display = "block";
}
}
}
<input type="checkbox" class="All" onclick="myFunction(this)">All
<input type="checkbox" class="select-one" onclick="myFunction(this)">Select 1
<input type="checkbox" class="select-two" onclick="myFunction(this)">Select 2
<table class="text">
<tr>
<td style="display:none">Checkbox is CHECKED!</td>
</tr>
<tr>
<td class="text-one" style="display:none">Checkbox is CHECKED 1!</td>
</tr>
<tr>
<td class="text-two" style="display:none">Checkbox is CHECKED 2!</td>
</tr>
</table>
关于javascript - 如何从选中的复选框中获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57033298/