【问题标题】:Jquery to add class to table row only applies to first row将类添加到表行的 Jquery 仅适用于第一行
【发布时间】:2016-12-06 01:45:16
【问题描述】:

我正在尝试使用 jquery 向表格行元素添加一个类,但它只适用于第一行。我正在使用 mysql 数据库填充表并使用 while 循环来显示表。

按下按钮后,我希望每一行在悬停时改变颜色。我想应用于表格行元素的类:

.hoverChange:hover
 {

     background-color: #66ccff

 }

显示所有数据的表格和while循环:

               <table border = 1> 
                <tr>
                <th>  ID  </th>
                <th>  Name  </th>
                <th>  Description  </th>
                <th>  Type  </th>
                <th>  Price  </th>
                <th>  Cost Price  </th>
                <th>  Stock Level </th>
                <th>  EAN  </th>
                </tr> 

                 <?php

                 while ($product_Info = mysqli_fetch_array($result,MYSQLI_ASSOC)) {


                         ?>

                        <tr id = tableRows>

                         <?php
                         echo "<td>" . $product_Info["product_ID"] . "</td>";
                         echo "<td>" . $product_Info["product_Name"] . "</td>";
                         echo "<td>" . $product_Info["product_Desc"] . "</td>";
                         echo "<td>" . $product_Info["product_Type"] . "</td>";
                         echo "<td>" . $product_Info["product_Price"] . "</td>";
                         echo "<td>" . $product_Info["product_Cost"] . "</td>";
                         echo "<td>" . $product_Info["product_Stock"] . "</td>";
                         echo "<td>" . $product_Info["product_ean"] . "</td>">                          


                         echo "<tr>";

                 }

                echo "</table>";

按钮:

<button type="button" id = "updateBtn" class="btn btn-info">Update</button>                 

最后是我正在使用的 jquery:

$(document).ready(function(){
$("#updateBtn").click(function(){
    $('#tableRows').addClass('hoverChange');
});
 });

【问题讨论】:

  • @JayBlanchard 哦,对,完全监督。无论如何,您的回答解释了这里出了什么问题
  • 谢谢@JayBlanchard,它现在工作正常。
  • 如果某个答案解决了您的问题,请考虑接受该答案。以下是meta.stackexchange.com/questions/5234/… 然后返回此处并对勾号/复选标记执行相同操作直到它变为绿色的方法。这通知社区,找到了解决方案。否则,其他人可能会认为问题仍然悬而未决,可能想要发布(更多)答案。您将获得积分,并鼓励其他人帮助您。 欢迎来到 Stack!

标签: javascript php jquery html


【解决方案1】:

您需要为表格行使用类而不是 ID。 ID's Must Be Unique,特别是因为当您尝试与这些元素交互时,它会导致 JavaScript 和 CSS 出现问题。

你有一些杂散的空格,你没有引用属性。这也可能在未来成为问题,即

<tr class="myClass">

【讨论】:

    【解决方案2】:

    您应该使用class 而不是id 属性来重复对象。整个页面的 ID 应该是唯一的。

    请注意代码中的空格;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-08
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 2011-04-24
      • 2021-11-28
      相关资源
      最近更新 更多