我正在尝试制作一个确认控件,如果我愿意,我可以在页面上多次使用。因此我使用了HTML,Bootstrap和JavaScript。出于调试原因,我想避免使用jQuery(尽可能多)(我知道Bootstrap我仍然可能需要使用其中一些)。
我的解决方案包含element.parentNode以便在单击时保持控件分离。我遇到的问题是,当点击时,我似乎无法从控件中获取特定按钮。我的意图是使用querySelectorAll()和保持我的代码清洁forEach(),但我似乎不成功:
const targetModal = $("#bs-modal-xl");
const positiveNodes = document.querySelectorAll(".foo");
const negativeNodes = document.querySelectorAll(".bar");
positiveNodes.forEach(node => node.addEventListener("click", function() {
const thisNode = this;
thisNode.classList.add("btn-success");
thisNode.parentNode.querySelectorAll(".bar").forEach(node => node.classList.remove("btn-warning"));
//How do I get the direct button containing the text "confirm?" after clicking any yes button and enable it?
console.log(thisNode.parentNode.parentNode)
console.log(thisNode.parentNode.parentNode.querySelectorAll("> button")); // returns Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Element': '> button' is not a valid selector.
console.log(thisNode.parentNode.parentNode.querySelectorAll("button")); // <-- returns nodelist of 3 buttons: "yes", "no" and "confirm?".
console.log(thisNode.parentNode.parentNode.parentNode.querySelectorAll(".confirmation-box > button")); // <-- returns nodelist of the available "confirm?" buttons, in this case 2 of them.
//I would not want the seperate ".confirmation-box" elements to interact with each other, these are independant elements.
}));
negativeNodes.forEach(node => node.addEventListener("click", function() {
this.classList.add("btn-warning");
this.parentNode.querySelectorAll(".foo").forEach(node => node.classList.remove("btn-success"));
}));
#foo-container {
padding: 5px;
}
通过使用我自己的包含类的自定义元素来分隔控件.confirmation-box。
控制的愿望是当点击“是”时,“确认?” 应该删除按钮的禁用状态,而单击“否”,应该禁用“确认?” 按钮。
是否可以使用querySelectorAll()和获得所需的元素forEach()?我可以避免循环(并使用索引)并使用这些方法吗?我忽略了什么吗?
所需元素应如下所示:单击 - >这 - >查找父.confirmation-box元素 - >查找子元素“确认?” 按钮。
慕田峪4524236
相关分类