2016-12-30 43 views
0

我創建了一個網站,用戶可以提問並允許其他人回覆。這些問題包含在div中,然後包含另一個div,其CSS屬性爲display: none如何訪問與引發事件的元素相關的特定div?

我在母親div中有一個按鈕,然後打開包含回覆或評論表單的div。我的代碼工作正常,

現在,我唯一的問題是,每當我點擊評論按鈕,它會打開所有其他答覆部分div,即使在用戶沒有點擊的問題。

如何獲得用戶點擊回覆按鈕的特定div並僅打開該母親div的回覆表單而不是所有其他人?

+0

你需要使用jQuery的DOM遍歷方法來尋找相關的元素。可悲的是,你沒有顯示任何實際的HTML代碼,也沒有你的JS的樣本,所以沒有人可以真正告訴你如何做到這一點。 –

+0

我有一個模板,它使用php數組從數據庫中獲取信息。然後我將其包含在我的html主體中以迴應數據庫中的所有問題。我的問題是,如何獲得特定的母版div,即e – user6284379

+0

在這種情況下,任何人都可以給你的唯一答案就是我的第一條評論 - 使用DOM遍歷。 –

回答

0

的jQuery:

$(".button").click(function(){ 
    //here the button element is pointed by -this-!!! 
    //so "this" is the element contained in your div... 
    $(this).parent("questionDiv") //<- will point to the div that contain the button 
    //so, having the button (this), you can get the parent element that contain the question and in it the mother div 
}); 

.parent(),還要檢查.closest().siblings()

希望這澄清我從你的問題:)

我要去承擔一些事情瞭解...

DOM:您的HTML代碼

<div class="mother"> 
    <div class="question"> 
     <button class="respBtn">Respond</button> 
    </div> 
    <div class="respond"> ..more elemnts.. </div> 
</div> 

的jQuery:

$(document).ready(function(){ 
     $(".respBtn").click(function(){ 
      console.log("click"); 
      //here goes the code that shows the div 
      let moderDiv = $(this).parents(".mother"); 
      console.log(moderDiv.html()); 
      moderDiv.find("div.respond").each(function(){ 
       $(this).show(); 
      }); 
     }); 
    }); 

CSS:

.respond{ 
     display : none ; 
    } 

這是一個例子... jQuery的需要知道哪個按鈕被按下ANS指向DOM的右側部分的護理。

希望這釐清我的想法:)

+0

好的謝謝。但是,如果所有這些問題都是從循環中回顯出來的,我的問題div都是一樣的。所以模板一遍又一遍地重複,直到循環結束。這意味着,所有的母親divs和問題divs都有相同的ID ...請幫助 – user6284379

+0

該id應該是定義唯一的,你可以在PHP腳本中改變echo循環用'class'改變'id'。另外如果你可以共享循環代碼,所以我可以看到DOM的結構... –

+0

$ questions = get_questions(); – user6284379

相關問題