<div class="container" style="overflow:scroll;height:480px">
<div class="form-check">
<input type="checkbox" checked="checked" class="form-check-input" id="1" name="1" value="N2">
<label class="form-check-label" for="1">N2</label>
</div>
<div class="form-check">
<input type="checkbox" class="form-check-input" id="3" name="3" value="Air">
<label class="form-check-label" for="3">Air</label>
</div>
</div>
$(function(){
$("input[name='submit']").on('click',function(){
debugger
$(this).closest('.container').each(function () {
debugger// 在这里获取所有子元素选中复选框的id
});
});
})
该回答引用chatgpt:
<!DOCTYPE html>
<html>
<head>
<title>Checkbox IDs</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container" style="overflow: scroll; height: 480px">
<div class="form-check">
<input type="checkbox" checked="checked" class="form-check-input" id="1" name="1" value="N2">
<label class="form-check-label" for="1">N2</label>
</div>
<div class="form-check">
<input type="checkbox" class="form-check-input" id="3" name="3" value="Air">
<label class="form-check-label" for="3">Air</label>
</div>
</div>
<button type="button" name="submit">Submit</button>
<script>
$(function () {
$("button[name='submit']").on('click', function () {
debugger;
$(this).prev('.container').find(":checkbox:checked").each(function () {
var checkboxId = $(this).attr("id");
console.log("Selected checkbox ID: " + checkboxId);
});
});
});
</script>
</body>
</html>
如果是Angular 7.x,则可以获取本机元素及其ID或属性。
myClickHandler($event) {
this.selectedElement = <Element>$event.target;
console.log(this.selectedElement.id)
this.selectedElement.classList.remove('some-class');
}
的HTML:
<div class="list-item" (click)="myClickHandler($event)">...</div>
要实现获取用户选中的复选框的id,可以通过以下步骤来实现:
<input type="checkbox" id="checkbox1">
<input type="checkbox" id="checkbox2">
<input type="checkbox" id="checkbox3">
function getSelectedCheckboxes() {
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var selectedIds = [];
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
selectedIds.push(checkboxes[i].id);
}
}
return selectedIds;
}
var selectedIds = getSelectedCheckboxes();
console.log(selectedIds);
这样就可以获取到用户选中的复选框的id了。