如果选中“全选”复选框,我想获取相应输入的容器内所有子节点的跨度文本值。
我当前的代码获取每个输入标签的“span”.text() 引用,但它只会记录 childNodes 复选框 (.leaflet-control-layers-selector) 的标签(例如“7211”),如果单独选择,或选择“全选”复选框 (.leaflet-control-layers-selector.leaflet-layerstree-sel-all-checkbox) 的标签(例如“住宿和餐饮服务”):
var htmlObject = layerControl.getContainer().querySelectorAll('input');
$(htmlObject).on("change", function(e) {
if ($(this).is(':checked'))
console.log($(this).siblings('span').text());
})
我可以引用“全选”输入,如果选中它,则迭代子节点并获取元素文本引用。像这样的事情:
var htmlObject = layerControl.getContainer().querySelectorAll('input');
$(htmlObject).on("change", function(e) {
if ($(this).is(':checked'))
console.log($(this).siblings('span').text());
selAll= ($(this).is('.leaflet-control-layers-selector.leaflet-layerstree-sel-all-checkbox:checked'))
if (selAll == true)
$(this).each(function () {
var sthisVal = (this.checked ? $(this).val() : "")
console.log(sthisVal)
})
})
但是,childNode 位于输入类之外,因此这会记录 SelectAll 输入复选框的“on”值。我必须引用它的容器或parentElement 来循环子节点。然后变量输出将记录文本标签。
最佳答案
我不确定我是否完全理解您想要做什么,但我认为我可以帮助您走上正确的道路。
// Get our container element, all subsequent jQuery calls will be scoped to this container - so only its children will be affected.
const $container = $('.container-1');
// Listen for changes on checkbox inputs that are NOT the Select All checkbox
$('input:not(.leaflet-layerstree-sel-all-checkbox)', $container).on("change", function(e) {
// Is the container's Select All Checkbox checked?
const isSelectAll = $('.leaflet-control-layers-selector.leaflet-layerstree-sel-all-checkbox', $container).is(':checked');
// If Select All is not checked, exit early.
if (!isSelectAll) { return; }
// Loop through all of the non-Select All checkboxes in the container
$('input:not(.leaflet-layerstree-sel-all-checkbox)', $container).each(function () {
if ($(this).is(':checked')) {
// If this checkbox is checked, log its sibling span's text
console.log($(this).siblings('span').text());
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container-1">
<input class="leaflet-control-layers-selector leaflet-layerstree-sel-all-checkbox" type="checkbox">
<span>Accomodation and Food Services</span>
<label>
<input class="leaflet-control-layers-selector" type="checkbox">
<span>7211</span>
</label>
</div>
关于javascript - jQuery 获取 div 类容器节点中全选输入的子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76009984/