【问题标题】:Creating dynamic class in a PHP foreach loop that a jQuery function can access在 jQuery 函数可以访问的 PHP foreach 循环中创建动态类
【发布时间】:2014-03-06 21:32:52
【问题描述】:

我有一个被证明是困难的问题。我有一个论坛,对一个问题有多个回复,从数据库中提取并使用 foreach 循环(PHP)显示。我想要一个“编辑您的响应”功能并有一个 jquery 功能,它将“显示”一个 HTML 块,其中包括每个响应下方的输入。问题是,当我在一个响应上选择编辑按钮时,它会在每个响应下激活 HRML 块,因为它针对“theDiv”类。是否有可能有一个只能选择一个的 jquery 函数......即,不知何故,foreach 循环中的每个响应都有一个动态创建的唯一类,jquery 函数可以针对该类?真的很难看到如何做到这一点......

  <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>

【问题讨论】:

标签: php jquery html foreach


【解决方案1】:

$(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 层次结构到包含 &lt;table&gt; 元素。 .prev(".theDiv") 选择紧接在它之前的元素,只要它有 class="theDiv"。这适用于您的 HTML,因为 table 和 div 是连续成对的。

【讨论】:

  • Barmar 和所有人,非常感谢。我是一个完整的 jquery 新手。您能否再解释一下您的答案...我会使用您上面引用的确切代码吗?再次感谢
  • 添加了一些解释。但是,如果您希望成为一名程序员,您需要学习如何阅读和理解文档。你不能指望人们用勺子喂你一切。这与jquery新手无关,只是程序员必备的技能。
  • 谢谢一百万。几个小时后会试试这个,然后告诉你。太棒了
  • 同意。我是一名有 6 个月编码经验的医生......你的帮助很好。非常感谢
  • Barmar ......只是想说声谢谢。这非常有效,并为我提供了新的学习领域……遍历 DOM。我只需要被引导到正确的方向。太棒了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-28
  • 2014-01-03
相关资源
最近更新 更多