2014-03-06 70 views
0

我有一個證明很困難的問題。我有一個論壇,對一個問題的多個迴應,從數據庫中拉出來,並使用foreach循環(PHP)顯示。我想要一個'編輯你的響應'函數,並有一個jquery函數,它將'顯示'一個包含每個響應下面輸入的HTML塊。問題是,當我在一個響應上選擇編輯按鈕時,它在每個響應下激活HRML,因爲它的目標是類「theDiv」。有沒有可能有一個jQuery的功能,可以選擇只有一個.......即使foreach循環中的每個響應都有一個動態創建的唯一類,jQuery的功能可以針對?真正地奮鬥,看看如何可以做到這一點.....在jQuery函數可以訪問的PHP foreach循環中創建動態類

<html> 
    <head> 
    <style type="text/css"> 
    .theDiv{ 
     display:none; 
    } 
    </style> 

    <link href="styles/threads_page.css" media="all" rel="stylesheet" type="text/css" /> 
    <script type="text/javascript" src="scripts/jquery-1.9.1.js"></script> 
    <script type="text/javascript"> 
    $(function() { 
     $(".show").click(function() { 
      $(".theDiv").show("normal"); 
     }); 
     $(".hide").click(function() { 
      $(".theDiv").hide("normal"); 
     }); 
     }); 
     </script> 
    </head> 
    <body> 

    <?php foreach($responses as $response):?> 
    <h3><?php echo $response->author . "<br/>"; 
     echo $response->content;     
     echo "<div class=\"theDiv\"> 
      <form action=\"question_gallery.php\" method=\"post\" class=\"form\"> 
      <table> 
      <tr> 
       <td>  
        Edit your response:   
         <input class=\"question_field\" name=\"question\"/> 
        </td> 
      </tr> 
      </table>     
     </form> 
     </div> 
     <table> 
     <tr> 
      <td> 
       <button class=\"show\">Edit response</button> 
      </td> 
     <td> 
      <button class=\"hide\">Close</button> 
     </td> 
     </tr> 
     </table> 
    ";} ?> 
    <?php endforeach; ?> 

    </body> 
    </html> 
+0

使用'$(this)'來定位被點擊的元素。 – Barmar

+1

從'this'開始,遍歷DOM到你想要的元素。 http://api.jquery.com/category/traversing/ –

回答

0

導線從$(this)開始DOM:

$(function() { 
    $(".show").click(function() { 
     $(this).closest("table").prev(".theDiv").show("normal"); 
    }); 
    $(".hide").click(function() { 
     $(this).closest("table").prev(".theDiv").hide("normal"); 
    }); 
}); 

(this)是你所點擊的元素。 .closest("table")搜索DOM層次結構到包含<table>元素。 .prev(".theDiv")選擇它之前的元素,只要它具有class="theDiv"。這適用於您的HTML,因爲表和div是按順序對。

+0

Barmar和所有人,非常感謝。我是一個jQuery完整的新手。你能解釋一下你的答案嗎?我會用上面引用的確切代碼嗎?再次感謝 – GhostRider

+0

添加了一些解釋。但是如果你希望把它作爲一個程序員,你需要學習如何閱讀和理解文檔。你不能指望別人給你一切東西。這與作爲jquery新手沒有任何關係,它只是程序員必備的技能。 – Barmar

+0

非常感謝。將在幾個小時內嘗試這個,並讓你知道。太棒了 – GhostRider