JQuery - 通过数据属性获取 div 数组并对其进行迭代

问题描述

我有 4 个 div,正在构建一个导航栏,用于确定在隐藏其他 div 的同时显示哪个。导航按钮如下:

<button data-button="personalInfo">Personal Info</button>
<button data-button="vehicleInfo">Vehicle Info</button>
<button data-button="vehicleCondition">Vehicle Condition</button>
<button data-button="ownershipInfo">Ownership Info</button>

div如下:

<div data-section="personalInfo">Personal Info</div>
<div data-section="vehicleInfo">Vehicle Info</div>
<div data-section="vehicleCondition">Vehicle Condition</div>
<div data-section="ownershipInfo">Ownership Info</div>

一个按钮被点击时,我想显示具有与按钮的 data-button 属性对应的 data-section 属性的 div。我编写了一个函数,它将特定的数据部分作为参数,目的是循环遍历每个 div 并将 d-none 的引导程序类应用于除数据部分与参数匹配的那个之外的每个 div。但是,我似乎无法以允许我迭代它们的方式获取数据部分的所有 div。这是 JQuery:

const personalInfoBtn = $(this).find('[data-button="personalInfo"]')
const vehicleInfoBtn = $(this).find('[data-button="vehicleInfo"]')
const vehicleConditionBtn = $(this).find('[data-button="vehicleCondition"]')
const ownershipInfoBtn = $(this).find('[data-button="ownershipInfo"]')

const switchFormSection = (dataSection) => {
    // All 3 of these methods do not get hold of the divs in a manner that allows me to loop over them and add/remove classes
    // const sections = $widget.attr("data-section");
    // const sections = $("div[data-section]");
    // const sections = $widget.data("section");

    sections.each(function(section){
        if(section === dataSection) {
            section.removeClass('d-none');
        } else {
            section.addClass('d-none');
        }
    })
}

personalInfoBtn.on("click",function(e) {
    switchFormSection("personalInfo");
})

vehicleInfoBtn.on("click",function(e) {
    switchFormSection("vehicleInfo");
})

vehicleConditionBtn.on("click",function(e) {
    switchFormSection("vehicleCondition");
})

ownershipInfoBtn.on("click",function(e) {
    switchFormSection("ownershipInfo");
})

对于如何实现这一点的任何帮助,或者是否有更智能的方式来执行此功能,我们不胜感激。

解决方法

由于按钮和 div 的数据属性完全匹配,因此无需单独指定每种不同的可能性。使用按钮上的点击侦听器,识别被点击元素的 data-button 属性,然后您可以遍历所有 <div> 并隐藏它们,然后显示与 data-button 匹配的那个:

const divs = $('[data-section]');
$('[data-button]').on('click',(e) => {
  divs.addClass('d-none');
  const name = e.target.dataset.button;
  divs
    .filter(`[data-section=${name}]`)
    .removeClass('d-none');
});
.d-none {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-button="personalInfo">Personal Info</button>
<button data-button="vehicleInfo">Vehicle Info</button>
<button data-button="vehicleCondition">Vehicle Condition</button>
<button data-button="ownershipInfo">Ownership Info</button>


<div data-section="personalInfo">Personal Info</div>
<div data-section="vehicleInfo" class="d-none">Vehicle Info</div>
<div data-section="vehicleCondition" class="d-none">Vehicle Condition</div>
<div data-section="ownershipInfo" class="d-none">Ownership Info</div>