3 回答

TA貢獻1853條經驗 獲得超9個贊
ID 必須是唯一的,并且由于您已經命名了所有 ID,因此post只有第一個 ID 才會被“看到”。使 ID 唯一,更改您的hide_post函數以接受要隱藏的 ID 名稱,并將唯一 ID 添加到您的onclick調用中。
改變
<div class="post" id="post">
類似的東西
<div class="post" id="post<?php echo $post['ID']; ?>">
然后改變
<div class="x_hover" onclick="hide_post()">
到
<div class="x_hover" onclick="hide_post('post<?php echo $post['ID']; ?>')">
最后,修改您的hide_post函數以接受要顯示或隱藏的 ID 的名稱。
function hide_post(idToHide){
if (idToHide.style.display = "block") {
idToHide.style.display = "none"
}
}

TA貢獻1865條經驗 獲得超7個贊
一種更干凈的方法是這樣做。
function hide_post() {
document.querySelectorAll('.post').forEach(v => {
if(v.style.display == block) v.style.display = none; }); }

TA貢獻1850條經驗 獲得超11個贊
當您使用getElementsByClassName它時,它會返回一個HTMLCollection. 如果您想要的話,您應該迭代元素并隱藏所有元素。現在您只是隱藏該集合的第 0 個元素。
var posts = document.getElementsByClassName("post");
for (let post of posts) {
if (post.style.display = "block") {
post.style.display = "none"
}
}
如果您打算隱藏單個帖子,您可以為 div 提供唯一的 id,并hide_post使用該帖子的 id 進行調用。你也應該用getElementById它。請注意,它不是復數。函數應該是這樣的:
function hide_post(postId){
var post = document.getElementById(postId);
if (post.style.display = "block") {
post.style.display = "none"
}
}
- 3 回答
- 0 關注
- 199 瀏覽
添加回答
舉報