首页 > 解决方案 > 将属性添加到在 jQuery 中,每个循环仅在第一次通过时?

问题描述

我有一个网页,可以从 SQL 表中打印出“库存”,并且可以通过在项目所在的列中输入要移除的数量来移除库存。

图1

注意:SQL 表有行“item”和“amount”(库存),我在打印的 HTML 表中添加了 amount 列,以便能够从库存中删除项目。

我希望能够标记每个输入标签以使属性“名称”等于项目名称。

前任:

第一排 -<input ... name='Apple'>

第二排——<input ... name='Banana'>

我在每个循环中使用 jQuery,它打印每一列并使用 attr() 添加属性,但主要问题是它为每一列添加了属性,但它覆盖了每一列的 name 属性。

前任:

第一关:<input ... name='Apple'>

第二关:<input ... name='10'>

我试过的:

我尝试通过添加一个 if 语句来解决这个问题所以它会添加一个,然后在下一次传递期间,if 条件将为 false,并且不会修改输入标签。

您将从代码中的注释中看到我还尝试了哪些其他方法,但似乎都没有给我所需的结果。

这是我用来打印 HTML 表格的 jQuery 代码:

function DISPLAY_INVENTORY(JSON_DATA) {
    var COL_NAMES = ['Item', 'Inventory', 'Amount'];

    var data = jQuery.parseJSON(JSON_DATA);
    var $TABLE_OBJ = $('<table class="table table-striped" >');
    $TABLE_OBJ.attr('id', 'student_table');
    $list.append($TABLE_OBJ);

    // $(output).append($TABLE_OBJ);

    //Print a table header
    var $ROW_OBJ = $('<tr>');
    var $THEAD = $('<thead class="thead-light">');
    $THEAD.append($ROW_OBJ);
    $TABLE_OBJ.append($THEAD);

    for (var j = 0; j < COL_NAMES.length; j++) {
      var $TB_HEADER = $('<th>');
      $TB_HEADER.html(COL_NAMES[j]);
      $ROW_OBJ.append($TB_HEADER);
    }

    $TBODY = $('<tbody>');

    //Print rows
    for (var i = 0; i < data.length; i++) {
      if (i == data.length - 1) {
        $TABLE_OBJ.append($TBODY);
      }

      $ROW_OBJ = $('<tr>');
      $TBODY.append($ROW_OBJ);

      //Print columns
      $.each(data[i], function(key, value) {
        // if (i % 2 == 0) {
        //   var ITEM_NAME = value;
        // }

        $COL_OBJ = $('<td>');
        $INP_OBJ = $('<input class="text-center form-control" type="text" size="3">');
        if (!$INP_OBJ.attr('name')) {
          $INP_OBJ.attr('name', value);

          // $INP_OBJ.attr('id', ITEM_NAME);
        }

        // $INP_OBJ.attr('name', ITEM_NAME);
        // $INP_OBJ.attr('id', ITEM_NAME);
        $COL_OBJ.html(value);
        $ROW_OBJ.append($COL_OBJ);
      });

      $ROW_OBJ.append($INP_OBJ);
    }
  }

JSON数据:

[{"item":"Apple","amount":"10"},
{"item":"Banana","amount":"11"},
{"item":"Corn","amount":"12"},
{"item":"Deli Sandwich","amount":"5"},
{"item":"Egg Plant","amount":"12"},
{"item":"French Fries","amount":"15"},
{"item":"Green Beans","amount":"21"},
{"item":"Hamburgers","amount":"7"},
{"item":"Ice Cream","amount":"3"},
{"item":"Jell-O","amount":"12"},
{"item":"Kiwi","amount":"8"},
{"item":"Lima Beans","amount":"32"},
{"item":"Mashed Potatoes","amount":"11"},
{"item":"Noodle Soup","amount":"54"},
{"item":"Orange","amount":"10"},
{"item":"Pear","amount":"5"},
{"item":"Quinoa","amount":"4"},
{"item":"Raisins","amount":"12"},
{"item":"String Cheese","amount":"16"},
{"item":"Tomato Soup","amount":"23"},
{"item":"Unsalted Nuts","amount":"19"},
{"item":"Vienna Sausage","amount":"24"},
{"item":"Wheat Bread","amount":"15"},
{"item":"Xavier Soup","amount":"17"},
{"item":"Yogurt","amount":"11"},
{"item":"Zucchini","amount":"12"}]

如果有人可以帮助我或用逻辑指出我正确的方向,我将不胜感激!谢谢你。

标签: javascriptjqueryhtml

解决方案


一种对代码进行最少修改的方法是使用一个变量,让我们调用它并仅在循环中等于“item”rowItemName时更新它的值。然后可以在设置输入名称时使用该变量:key$.each()

$list = $('#list');

function DISPLAY_INVENTORY(JSON_DATA) {
  var COL_NAMES = ['Item', 'Inventory', 'Amount'];

  var data = jQuery.parseJSON(JSON_DATA);
  var $TABLE_OBJ = $('<table class="table table-striped" >');
  $TABLE_OBJ.attr('id', 'student_table');
  $list.append($TABLE_OBJ);

  // $(output).append($TABLE_OBJ);

  //Print a table header
  var $ROW_OBJ = $('<tr>');
  var $THEAD = $('<thead class="thead-light">');
  $THEAD.append($ROW_OBJ);
  $TABLE_OBJ.append($THEAD);

  for (var j = 0; j < COL_NAMES.length; j++) {
    var $TB_HEADER = $('<th>');
    $TB_HEADER.html(COL_NAMES[j]);
    $ROW_OBJ.append($TB_HEADER);
  }

  $TBODY = $('<tbody>');

  //Print rows
  for (var i = 0; i < data.length; i++) {
    if (i == data.length - 1) {
      $TABLE_OBJ.append($TBODY);
    }

    $ROW_OBJ = $('<tr>');
    $TBODY.append($ROW_OBJ);
    
    

    //Print columns
    var rowItemName;
    $.each(data[i], function(key, value) {
      if (key === 'item') {
        rowItemName = value;
      }
      // if (i % 2 == 0) {
      //   var ITEM_NAME = value;
      // }

      $COL_OBJ = $('<td>');
      $INP_OBJ = $('<input class="text-center form-control" type="text" size="3">');
      if (!$INP_OBJ.attr('name')) {
        $INP_OBJ.attr('name', rowItemName);

        // $INP_OBJ.attr('id', ITEM_NAME);
      }

      // $INP_OBJ.attr('name', ITEM_NAME);
      // $INP_OBJ.attr('id', ITEM_NAME);
      $COL_OBJ.html(value);
      $ROW_OBJ.append($COL_OBJ);
    });

    $ROW_OBJ.append($INP_OBJ);
  }
}

// using JSON.stringify() here only for demonstration
// so I can pass JSON as a string as the function expects
DISPLAY_INVENTORY(JSON.stringify([{"item":"Apple","amount":"10"},
{"item":"Banana","amount":"11"},
{"item":"Corn","amount":"12"},
{"item":"Deli Sandwich","amount":"5"},
{"item":"Egg Plant","amount":"12"},
{"item":"French Fries","amount":"15"},
{"item":"Green Beans","amount":"21"},
{"item":"Hamburgers","amount":"7"},
{"item":"Ice Cream","amount":"3"},
{"item":"Jell-O","amount":"12"},
{"item":"Kiwi","amount":"8"},
{"item":"Lima Beans","amount":"32"},
{"item":"Mashed Potatoes","amount":"11"},
{"item":"Noodle Soup","amount":"54"},
{"item":"Orange","amount":"10"},
{"item":"Pear","amount":"5"},
{"item":"Quinoa","amount":"4"},
{"item":"Raisins","amount":"12"},
{"item":"String Cheese","amount":"16"},
{"item":"Tomato Soup","amount":"23"},
{"item":"Unsalted Nuts","amount":"19"},
{"item":"Vienna Sausage","amount":"24"},
{"item":"Wheat Bread","amount":"15"},
{"item":"Xavier Soup","amount":"17"},
{"item":"Yogurt","amount":"11"},
{"item":"Zucchini","amount":"12"}]
))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="list"></div>

但是,您可以大大减少和简化代码,同时甚至提高性能(通过 jQuery 添加每个 HTML 元素比将标记构建为字符串然后一次性将其添加到 DOM 成本更高):

$list = $('#list');

function DISPLAY_INVENTORY(JSON_DATA) {
  var COL_NAMES = ['Item', 'Inventory', 'Amount'];

  var data = $.parseJSON(JSON_DATA);
  var TABLE_MARKUP = '<table class="table table-striped" id="student_table">';
  TABLE_MARKUP += '<tr><th>' + COL_NAMES.join('</th><th>') + '</th><tbody>';
  
  
  $.each(data, function(key, row) {
    TABLE_MARKUP += '<tr><td>' + row.item + '</td><td>' + row.amount + '</td><td><input class="text-center form-control" type="text" size="3" name="' + row.item + '"></td></tr>';
  });
  
  TABLE_MARKUP += '</tbody>';
  $list.html(TABLE_MARKUP);
}

// using JSON.stringify() here only for demonstration
// so I can pass JSON as a string as the function expects
DISPLAY_INVENTORY(JSON.stringify([{"item":"Apple","amount":"10"},
{"item":"Banana","amount":"11"},
{"item":"Corn","amount":"12"},
{"item":"Deli Sandwich","amount":"5"},
{"item":"Egg Plant","amount":"12"},
{"item":"French Fries","amount":"15"},
{"item":"Green Beans","amount":"21"},
{"item":"Hamburgers","amount":"7"},
{"item":"Ice Cream","amount":"3"},
{"item":"Jell-O","amount":"12"},
{"item":"Kiwi","amount":"8"},
{"item":"Lima Beans","amount":"32"},
{"item":"Mashed Potatoes","amount":"11"},
{"item":"Noodle Soup","amount":"54"},
{"item":"Orange","amount":"10"},
{"item":"Pear","amount":"5"},
{"item":"Quinoa","amount":"4"},
{"item":"Raisins","amount":"12"},
{"item":"String Cheese","amount":"16"},
{"item":"Tomato Soup","amount":"23"},
{"item":"Unsalted Nuts","amount":"19"},
{"item":"Vienna Sausage","amount":"24"},
{"item":"Wheat Bread","amount":"15"},
{"item":"Xavier Soup","amount":"17"},
{"item":"Yogurt","amount":"11"},
{"item":"Zucchini","amount":"12"}]
))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="list"></div>

它甚至可以使用模板文字JSON.parse()和 native进一步简化forEach(),具体取决于所需的旧版浏览器支持。瞧,不需要 jQuery:

function DISPLAY_INVENTORY(JSON_DATA) {
  var COL_NAMES = ['Item', 'Inventory', 'Amount'];

  var data = JSON.parse(JSON_DATA);
  var TABLE_MARKUP = `<table class="table table-striped" id="student_table">
    <tr><th>${COL_NAMES.join('</th><th>')}</th><tbody>`;
  
  data.forEach((row) => {
    TABLE_MARKUP += `<tr><td>${row.item}</td><td>${row.amount}</td><td><input class="text-center form-control" type="text" size="3" name="${row.item}"></td></tr>`;
  });
  
  TABLE_MARKUP += '</tbody>';
  document.getElementById('list').innerHTML = TABLE_MARKUP;
}

// using JSON.stringify() here only for demonstration
// so I can pass JSON as a string as the function expects
DISPLAY_INVENTORY(JSON.stringify([{"item":"Apple","amount":"10"},
{"item":"Banana","amount":"11"},
{"item":"Corn","amount":"12"},
{"item":"Deli Sandwich","amount":"5"},
{"item":"Egg Plant","amount":"12"},
{"item":"French Fries","amount":"15"},
{"item":"Green Beans","amount":"21"},
{"item":"Hamburgers","amount":"7"},
{"item":"Ice Cream","amount":"3"},
{"item":"Jell-O","amount":"12"},
{"item":"Kiwi","amount":"8"},
{"item":"Lima Beans","amount":"32"},
{"item":"Mashed Potatoes","amount":"11"},
{"item":"Noodle Soup","amount":"54"},
{"item":"Orange","amount":"10"},
{"item":"Pear","amount":"5"},
{"item":"Quinoa","amount":"4"},
{"item":"Raisins","amount":"12"},
{"item":"String Cheese","amount":"16"},
{"item":"Tomato Soup","amount":"23"},
{"item":"Unsalted Nuts","amount":"19"},
{"item":"Vienna Sausage","amount":"24"},
{"item":"Wheat Bread","amount":"15"},
{"item":"Xavier Soup","amount":"17"},
{"item":"Yogurt","amount":"11"},
{"item":"Zucchini","amount":"12"}]
))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="list"></div>


推荐阅读