繁体   English   中英

更新多个条目表的特定行

[英]Update specific row of table of multiple entries

我有一张顾客桌子。 每个客户都有名字和姓氏。 该表的两个文本字段是可编辑的。 因此,用户可以在按保存时更新信息。 问题是我无法获取特定的行信息,只能获取第一行结果

我尝试将名称与输入字段匹配,但没有成功。

<?php foreach($customer as $each){ ?>
    <td class="first_name" id="first" contenteditable="true"><?php echo 
    $each['first_name']; ?></td>
    <td class="last_name" id="last"  contenteditable="true"><?php echo 
    $each['last_name']; ?></td>
    <td >   <button type="button" onclick="save('<?php echo $each['first_name'];? 
    >','<?php echo $each['last_name'];?>');" >Save</button></td>
    <? } ?>

<script type="text/javascript">
    function save(first,second) {
      <?php foreach($customer as $each){?>
        var first_name = "<?php echo $each['first_name']?>";
        var last_name = "<?php echo $each['last_name']?>";
        if (first_name==first && last_name == second){
          var fname = document.querySelectorAll(".first_name");
          console.log(fname[0]);
        }
        <?php } ?>

      }
 </script>

您将不得不使用其他查询选择器。 为要选择的元素分配一个类名或属性(例如,使用.name进行查询的name ),然后querySelectorAll方法将返回与查询匹配的元素数组。

我看到的主要问题是,您使用phpjavascript函数内创建了不必要的foreach循环。

您可以动态创建表及其中的内容,这很好。 但是javascript并不关心这一点,因此您不应该使用php创建javascript。 所以我会这样做。

我将td封装在tr的原因中,我假设您将这些数据放入tr中。

<?php foreach($customer as $each){ ?>
  <tr class="customer-row">
    <td class="first_name" contenteditable="true"><?php echo 
    $each['first_name']; ?></td>
    <td class="last_name" contenteditable="true"><?php echo 
    $each['last_name']; ?></td>
    <td><button type="button" class="save">Save</button></td>
  </tr>
<? } ?>

然后在php foreach循环之外,我将创建我的脚本。

<script type="text/javascript">
var saveBtn = document.querySelectorAll(".save");

for(var i = 0; i < saveBtn.length; i++) {
  // attach click event to every button.
  saveBtn[i].addEventListener("click", function() {
    var _this = this;
    var _tr = _this.closest(".customer-row");
    var fname = _tr.querySelector(".first_name").innerText;
    var lname = _tr.querySelector(".last_name").innerText;
    console.log("Name: ", fname + " " + lname");
    // below you can implement your check name logic...
  }
}
</script>

我不确定我的js是否不会引发错误,但不能100%地确定您应该将server-side client-side逻辑与client-side逻辑分开。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM