如果选中“全选”复选框,我想获取相应输入容器内所有子节点的跨度文本值。
我当前的代码获取每个输入标签的 '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)
})
})
但是,子节点在输入类之外,因此这会记录 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>
我想出了如何使用父/子节点引用获取所选子节点的文本标签。
var htmlObject = layerControl.getContainer().querySelectorAll('input');
$(htmlObject).on("change", function(e) {
if ($(this).is('.leaflet-control-layers-selector.leaflet-layerstree-sel-all-checkbox:checked')) {
console.log($(this).siblings('span').text())
var ancestors = $(this).parents(".leaflet-layerstree-node")[0].children[1].outerText;
console.log(ancestors)
}
else {
if ($(this).is(':checked'))
console.log($(this).siblings('span').text());
}
})
如果选择了 selectAll 复选框,这将输出所有子节点的文本标签。
[#] 与特定示例相关的属性。