【发布时间】:2021-06-18 09:55:49
【问题描述】:
我有 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>
单击按钮时,我想显示具有与按钮的 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");
})
任何有关如何实现这一点的帮助,或者如果有执行此功能的更智能方法,我们将不胜感激。
【问题讨论】:
标签: jquery loops attributes custom-attributes