[英]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.