我正在嘗試使用 html、css 和 javascript 創建網站儀表板。在儀表板選擇選單中,我添加了幾個選項供用戶選擇要在右側網頁上顯示的資料。對于每個選擇選項,我使用 forEach 回圈添加了一個單擊 EventListner 函式。當用戶單擊一個選項時,我得到該元素的 ID 并將其與要顯示的資料表 ID 匹配。然后將 classname .active{display: block;} 添加到所選元素顯示用戶選擇的表。
When firsttime user select elemen javascript eventListner Functio wokrs, But when user select the same element for the second time ` document.getElementById(elementId)` return null and whole program crashes.
<div class="dashboard">
<div class="menu">
<div class="menu-btns">
<a id="dashboard" class="menu-btn">Dashboard</a>
<a id="posted" class="menu-btn">Posted Jobs</a>
<a id="applicants" class="menu-btn">Applicants</a>
<a id="newJob" class="menu-btn">New Job</a>
<a id="myProfile" class="menu-btn">My Profile</a>
</div>
</div>
<div >
<div id="main-dashboard" ></div>
<div id="publihed-posts" >
<table >
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Published Date</th>
<th>Closing Date</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Senior Software Engineer</td>
<td>01/02/2022</td>
<td>01/02/2022</td>
<td><button >Edit</button></td>
<td><button >Delete</button></td>
</tr>
</tbody>
</table>
</div>
<div id="recieved-applicants" >
<table >
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Title</th>
<th>Applied Date</th>
<th>Check</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div id="vacancy-published" >
<p >Vacancy Publish Form</p>
<form action="">
<div>Form Content<div/>
</form>
</div>
let dashboardBtnEl = document.querySelectorAll(".menu-btn");
let elementId;
dashboardBtnEl.forEach((btn) => {
btn.addEventListener("click", (event) => {
let selectedEl = event.target.id;
if (elementId) document.getElementById(elementId).remove("active");
switch (selectedEl) {
case "dashboard":
elementId = "main-dashboard";
break;
case "posted":
elementId = "publihed-posts";
break;
case "applicants":
elementId = "recieved-applicants";
break;
case "newJob":
elementId = "vacancy-published";
break;
case "myProfile":
elementId = "edit-profile";
break;
}
console.log(elementId);
console.log(document.getElementById(elementId);
document.getElementById(elementId).classList.add("active");
}); });

uj5u.com熱心網友回復:
你的問題在這里
document.getElementById(elementId).remove("active");
改變它
document.getElementById(elementId).classList.remove("active");
您正在從 DOM 中洗掉匹配的元素
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/475504.html
標籤:javascript
上一篇:在SpringBoot中通過ActiveMQArtemis發送異步訊息時如何創建會話工廠?
下一篇:按ID查找和更新嵌套陣列元素
