2014-03-06 32 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