【问题标题】:Change Row Color of Table When TD Is Clicked单击TD时更改表格的行颜色
【发布时间】:2017-04-09 03:50:14
【问题描述】:

背景

我正在用 php.ini 动态创建一个表。在<td> 之一中,我添加了js function。当用户单击该字段时,AJAX 函数将运行并从数据库表中删除该行。

我试图弄清楚如何定位该特定行以更新视图以显示该行已被删除。我要么删除整行,要么将颜色更改为红色,以向用户显示该行已从数据库中删除。

问题

当用户点击动态创建表的<td> 内的链接时,如何定位整行以便对点击的行执行 DOM 操作?

示例代码表

注意底部的onClick function。该函数运行,当 AJAX 函数成功时,我想删除该行或更改它的颜色。

    <tr>
      <th>Customer ID</th>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Phone</th>
      <th>Email</th>
      <th>Download Letter</th>
      <th>Template ID</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><?php echo $value->customer_id; ?></td>
      <td><?php echo $value->fname; ?></td>
      <td><?php echo $value->lname; ?></td>
      <td><?php echo $value->phone; ?></td>
      <td><?php echo $value->email; ?></td>
      <td><a href="<?php echo $value->pdf_file_path; ?>"><?php echo $value->template_heading; ?></a></td>
      <td><?php echo $value->temp_id; ?></td>
       <td>
            <a class="blue-text"><i class="options fa fa-user"></i></a>
            <a class="green-text"><i class="options fa fa-pencil"></i></a>
            <a class="red-text" href="#" onClick="removePDF(user_id, customer_id, temp_id)"><i class="options fa fa-times"></i></a>
        </td>
    </tr>

AJAX 函数

function removePDF(user_id, customer_id, temp_id){
    return $.ajax({
        url: 'https://www.example.com/script.php',
        type: 'GET',
        cache: false,
        data: {
            user_email: user_email,
            user_id: user_id,
            customer_id: customer_id,
            temp_id: temp_id,
        },
        success: function(data){
            console.log(data);
        }
    });
}

【问题讨论】:

  • temp_id 对于每一行都是唯一的?
  • 不是父亲。电子邮件加上临时 ID 制作一个网址。
  • 还有一件事是tr 正在通过任何循环生成?
  • 是的,整个表都在 for 循环中

标签: javascript php jquery html ajax


【解决方案1】:

由于 HTML 是通过脚本生成的,因此您可以设置一些计数器并为每个 &lt;tr&gt; 标签添加唯一 ID,然后通过 removePDF() JS 方法传递该计数器。

HTML 代码示例

<tr id="unique_num_<?= $unique_ctr; ?>">
    <!-- ... -->
    <!-- ... -->
    <td> 
        <a class="blue-text"><i class="options fa fa-user"></i></a>
        <a class="green-text"><i class="options fa fa-pencil"></i></a>
        <a class="red-text" href="javascript:void(0);" onClick="removePDF(user_id, customer_id, temp_id, <?= $unique_ctr; ?>)"><i class="options fa fa-times"></i></a>
    </td>
</tr>

示例 JS 代码将是

function removePDF(user_id, customer_id, temp_id, tr_num) {
    //...
    //...
    success: function (data) {
        console.log(data);
        $('#unique_num_' + tr_num).remove();
        //or
        $('#unique_num_' + tr_num).addClass('my_class');
        //...
    }
    //...
    //...
}

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 2022-01-19
    • 2013-11-28
    • 1970-01-01
    • 2014-12-29
    相关资源
    最近更新 更多