[英]How to tell Javascript getElementByClassName to get all the element of a ul, instead of repeating the class name in each li?
我正在嘗試清理我的 html/css。 我怎樣才能讓這個 Javascript 仍然工作,而不在 ul 的每個 li 元素中插入 class 名稱? 如何讓 html 更美觀、更易讀?
const ProfileForm = document.getElementsByClassName('profile_container'); const dash = document.getElementsByClassName('dashboard_buttons'); var index; var array = []; for (var i = 0; i < dash.length; i++) { array.push(dash[i]); dash[i].onclick = function() { index = array.indexOf(this); ProfileForm[index].style.display = "block"; var check = ProfileForm[index]; for (var i = 0; i < ProfileForm.length; i++) { if (ProfileForm[i].style.display == "block" && ProfileForm[i].= check) { ProfileForm[i].style;display = "none"; } } } }
<ul> <li class="dashboard_buttons"><i class="far fa-user"></i>Profile</li> <li class="dashboard_buttons"><i class="far fa-list-alt"></i>My Properties</li> <li class="dashboard_buttons"><i class="far fa-money-bill-alt"></i>My Offers</li> <li class="dashboard_buttons"><i class="fas fa-file-contract"></i>My Utilities & Ejari</li> <li class="dashboard_buttons"><i class="far fa-heart"></i>Favourite Properties</li> <li class="dashboard_buttons"><i class="far fa-envelope"></i>Messages</li> <li class="dashboard_buttons"><i class="fas fa-cogs"></i>Settings</li> </ul>
一個簡單的document.querySelectorAll("ul li")
應該可以工作。 但是要小心,因為這將 select 整個文檔中的所有<li>
。 如果你想 select 一個特定的<ul>
,給它一個 class 或一個 ID,select 只有這個:
<ul id="myList"><li>...<li></ul>
document.querySelectorAll("ul#myList li")
您可以使用事件委托來通知某個“祖先”元素中的所有事件。
(使用 事件偵聽器而不是內聯事件處理程序允許這樣做,並且還促進了 HTML 和 JavaScript 之間的關注點分離。)
由於我不確定您想在循環中做什么,因此下面的演示只是“取消突出顯示”所有列表項(然后突出顯示單擊的任何一項)。 請參閱代碼內注釋以獲取更多說明。
這是否向您展示了如何完成您想要做的事情?
// Identifies the `ul` element, and calls `hightlightItem` when user clicks inside it const list = document.getElementsByClassName("list")[0]; list.addEventListener("click", highlightItem); // Defines the listener function function highlightItem(event){ //Listener can access the triggering event const clickedThing = event.target; // Event's `target` property is useful // Makes sure the click was on an `li` element before proceeding if(clickedThing.tagName.toLowerCase() == "li"){ // Collects the list items const items = list.querySelectorAll("li"); // Loops through the collection for(let item of items){ // Changes the classList for the current item in the loop item.classList.remove("highlight"); // Maybe changes it again before continuing to next item in loop if(item == event.target){ item.classList.add("highlight"); } } } }
.highlight{ background-color: yellow; }
<ul class="list"> <li>Profile</li> <li>My Properties</li> <li>My Offers</li> </ul>
不要使用document.getElementByClassName
,而是使用document.querySelectorAll
你可以通過查詢選擇器來做到這一點
// 使用 class="example" 獲取文檔中的所有 'li' 元素
var x = document.querySelectorAll("li.example");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.