JQuery - 通过数据属性获取 div 数组并迭代它们

JQuery - get array of divs by data attribute and iterate over them

我有 4 个 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>

单击按钮时,我想显示 div 以及与按钮的数据按钮属性相对应的数据部分属性。我编写了一个将特定数据部分作为参数的函数,目的是遍历每个 div 并将 d-none 的 bootstrap class 应用于除了数据部分与参数匹配的那个之外的每个。但是,我似乎无法通过数据部分以允许我迭代它们的方式获取所有 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>