简体   繁体   English

更改 HTML 表中 td 元素的颜色,然后使用 AJAX 写入数据库

[英]Changing color of td element in HTML table and then using AJAX to write to DB

I have a table of results retrieved from a MYSQl database with each TR having a unique ID and Class.我有一个从 MYSQl 数据库中检索到的结果表,每个 TR 都有一个唯一的 ID 和类。 When clicking on the TD in a row, the script toggles through various colors depending on the order status, and then writes on each toggle back to the DB using AJAX.当连续点击 TD 时,脚本会根据订单状态切换各种颜色,然后使用 AJAX 将每个切换写回数据库。 The problem I am having is that the color changes the last table row td and not the current clicked row td.我遇到的问题是颜色更改了最后一个表格行 td 而不是当前单击的行 td​​。 I am a noob to JS and Jquery and have read that the problem may be "hoisting" which has had me confused for a few days now.我是 JS 和 Jquery 的菜鸟,并且读到问题可能是“提升”,这让我困惑了几天。 Any help is greatly appreciated.任何帮助是极大的赞赏。

<td id="<?php echo $row[ 'order_id' ]; ?>" class="<?php echo $row[ 'order_id' ]; ?> white"
    onclick="changeBackground(this.id)"><?php echo $row[ 'order_id' ]; ?></td>

<script>
  function getSelected() {
    return document.getElementsByClassName(<?php echo $row[ 'order_id' ]; ?>);
  }

  function changeBackground(id) {
    var all = getSelected();
    var x = id
    alert(x);
    for (var i = 0; i < all.length; i++) {
      var color = all[i].classList;
      
      if (color.contains("white")) {
        all[i].classList.add("red");
        all[i].classList.remove("white");
        $.ajax({
          type: "POST",
          url: 'update_color.php',
          data: {color: 2},
          success: function (data) {
            console.log(data);
          },
        });
        
      } else if (color.contains("red")) {
        all[i].classList.add("green");
        all[i].classList.remove("red");
        $.ajax({
          type: "POST",
          url: 'update_color.php',
          data: {color: 3},
          success: function (data) {
            console.log(data);
          },
        });

      } else if (color.contains("green")) {
        all[i].classList.add("pink");
        all[i].classList.remove("green");
        $.ajax({
          type: "POST",
          url: 'update_color.php',
          data: {color: 4},
          success: function (data) {
            console.log(data);
          },
        });
        
      } else if (color.contains("pink")) {
        all[i].classList.add("yellow");
        all[i].classList.remove("pink");
        $.ajax({
          type: "POST",
          url: 'update_color.php',
          data: {color: 5},
          success: function (data) {
            console.log(data);
          },
        });
        
      } else if (color.contains("yellow")) {
        all[i].classList.add("white");
        all[i].classList.remove("yellow");
        $.ajax({
          type: "POST",
          url: 'update_color.php',
          data: {color: 1},
          success: function (data) {
            console.log(data);
          },
        });
      }

    }
  }
</script>

If you are able to modify the HTML output slightly I believe the above Javascript can be significantly simplified but I should stress the following is untested.如果您能够稍微修改 HTML 输出,我相信上面的 Javascript 可以显着简化,但我应该强调以下内容未经测试。 The order_id seems odd within the classes assigned to an element - presumably an integer which is not valid anyway as a class - perhaps if this were assigned as a dataset attribute it would make more sense and can still be referenced in your javascript code if needed. order_id在分配给元素的类中似乎很奇怪 - 大概是一个无论如何作为类都无效的整数 - 也许如果将其分配为dataset属性会更有意义,并且如果需要,仍然可以在您的 javascript 代码中引用。 To set the class simply as one of the various colours through which you cycle would help!将类简单地设置为您循环的各种颜色之一会有所帮助!

So, perhaps changing the HTML like this:所以,也许像这样改变 HTML:

<td data-id="<?php echo $row['order_id'];?>" class="white">
    <?php echo $row['order_id'];?>
</td>

Then the Javascript然后是 Javascript

const matrix={
    'white':'red',
    'red':'green',
    'green':'pink',
    'pink':'yellow',
    'yellow':'white'
};

document.querySelectorAll('table td').forEach( td=>td.addEventListener('click',function(e){
    let id=this.dataset.id;
    let colour=this.className;
    let keys=Object.values( matrix );
    
    this.classList.remove( colour );
    this.classList.add( matrix[ colour ] );
    
    
    
    let fd=new FormData();
        fd.set('color', keys.indexOf( colour) );
        fd.set('id',id);
        
    fetch( 'update_color.php',{ method:'post',body:fd} )
        .then(r=>r.text())
        .then(text=>{
            console.log(text)
        })
}))

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

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