我正在嘗試制作一個(gè)確認(rèn)控件,如果我愿意,我可以在頁(yè)面上多次使用。因此我使用了HTML,Bootstrap和JavaScript。出于調(diào)試原因,我想避免使用jQuery(盡可能多)(我知道Bootstrap我仍然可能需要使用其中一些)。我的解決方案包含element.parentNode以便在單擊時(shí)保持控件分離。我遇到的問題是,當(dāng)點(diǎn)擊時(shí),我似乎無法從控件中獲取特定按鈕。我的意圖是使用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;}JSFiddle通過使用我自己的包含類的自定義元素來分隔控件.confirmation-box??刂频脑竿钱?dāng)點(diǎn)擊“是”時(shí),“確認(rèn)?” 應(yīng)該刪除按鈕的禁用狀態(tài),而單擊“否”,應(yīng)該禁用“確認(rèn)?” 按鈕。是否可以使用querySelectorAll()和獲得所需的元素forEach()?我可以避免循環(huán)(并使用索引)并使用這些方法嗎?我忽略了什么嗎?所需元素應(yīng)如下所示:?jiǎn)螕?- >這 - >查找父.confirmation-box元素 - >查找子元素“確認(rèn)?” 按鈕。
我可以使用queryselector和foreach在javascript中獲得直接元素嗎?
牧羊人nacy
2019-04-18 18:13:57