JQuery Как изменить цвет фона строки для каждой отдельной строки?

У меня такой вопрос, как я могу изменить цвет фона для каждой отдельной строки?

Например, у меня есть таблица

Для этих строк я хочу сделать другой цвет, например красный.

HTML:

    <table>
    <thead>
        <tr>
            <th></th>
            <th>Data</th>
            <th>Data</th>
            <th>Data</th>
            <th>Data</th>
            <th>Data</th>
            <th>Data</th>
            <th>Data</th>
        </tr>
    </thead>
    <tbody class = "tableData">
    </tbody>
</table>

JS:

var lpmsData = [
    { item: "111000355B", order: "9999999999", actual: "403", target: "404", defects: "1", efficiency: 89, pefomance: 78, oee: "N/A", startTime: "06:45:44" },
    { item: "102211549B", order: "8888888887", actual: "504", target: "366", defects: "123", efficiency: 125, pefomance: 96, oee: "N/A", startTime: "05:35:64" }
];

var timeShedule = [
    { firstShift: ["05:45 - 07:00", "07:00 - 08:00", "08:00 - 09:00", "09:00 - 10:00", "10:00 - 11:00", "11:00 - 12:00", "12:00 - 13:00", "13:00 - 14:00", "14:00 - 14:45",]}
];

function buildTable() {
    $.each(lpmsData, function (i, data) {
        var categoryBuild = '<tr><td width = "150">' + timeShedule[0].firstShift[i] + '</td><td>' + data.item + '</td><td>' + data.actual + '</td><td>' + data.target + '</td><td>' + data.defects + '</td><td>' + data.efficiency + '</td><td>' + data.pefomance + '</td><td>' + data.oee + '</td></tr>';
        if (data.efficiency <= 50) {
            $(this).css("background-color", "blue");
        }
        $('.tableData').append(categoryBuild);
    });

}

Я пытаюсь использовать этот тип кода, но получил:

Итак, есть идеи, как это сделать?

Предполагая, что вы перебираете каждую строку, используйте $(this).css("background-color", "blue");

Carsten Løvbo Andersen 21.05.2019 08:30

пожалуйста, покажите, как вы создаете таблицу, а также html

brk 21.05.2019 08:30

@CarstenLøvboAndersen да, я использую цикл, но этот код не работает

qunz666 21.05.2019 08:31

@ qunz666, тогда вы должны предоставить нам свою HTML-таблицу и соответствующий код jQuery.

Carsten Løvbo Andersen 21.05.2019 08:32

@brk отредактировал вопрос

qunz666 21.05.2019 08:33
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
5
34
3
Перейти к ответу Данный вопрос помечен как решенный

Ответы 3

Ответ принят как подходящий

Вы можете переместить оператор if после метода append:

$('.tableData').append(categoryBuild);
if (data.efficiency <= 50) {
  $('.tableData tr:last').css("background-color", "blue");
}

Демо

var lpmsData = [{
    item: "111000355B",
    order: "9999999999",
    actual: "403",
    target: "404",
    defects: "1",
    efficiency: 89,
    pefomance: 78,
    oee: "N/A",
    startTime: "06:45:44"
  },
  {
    item: "102211549B",
    order: "8888888887",
    actual: "504",
    target: "366",
    defects: "123",
    efficiency: 125,
    pefomance: 96,
    oee: "N/A",
    startTime: "05:35:64"
  },
  {
    item: "112255458C",
    order: "7777777777",
    actual: "777",
    target: "555",
    defects: "1",
    efficiency: 155,
    pefomance: 102,
    oee: "N/A",
    startTime: "07:44:44"
  },
  {
    item: "111225445G",
    order: "6666666666",
    actual: "403",
    target: "404",
    defects: "1",
    efficiency: 34,
    pefomance: 78,
    oee: "N/A",
    startTime: "11:55:09"
  },
  {
    item: "584844455A",
    order: "5555555555",
    actual: "905",
    target: "905",
    defects: "1",
    efficiency: 100,
    pefomance: 78,
    oee: "N/A",
    startTime: "12:45:44"
  },
  {
    item: "111000354B",
    order: "9999999999",
    actual: "403",
    target: "404",
    defects: "1",
    efficiency: 89,
    pefomance: 78,
    oee: "N/A",
    startTime: "13:45:44"
  },
  {
    item: "102253212B",
    order: "8888888887",
    actual: "504",
    target: "366",
    defects: "123",
    efficiency: 125,
    pefomance: 96,
    oee: "N/A",
    startTime: "13:55:44"
  },
  {
    item: "112241678C",
    order: "7777777777",
    actual: "777",
    target: "555",
    defects: "1",
    efficiency: 50,
    pefomance: 102,
    oee: "N/A",
    startTime: "14:15:44"
  },
  {
    item: "111225456G",
    order: "6666666666",
    actual: "403",
    target: "404",
    defects: "1",
    efficiency: 89,
    pefomance: 78,
    oee: "N/A",
    startTime: "14:22:46"
  },
  {
    item: "584844000A",
    order: "5555555555",
    actual: "905",
    target: "905",
    defects: "1",
    efficiency: 100,
    pefomance: 78,
    oee: "N/A",
    startTime: "14:36:13"
  }
];

var timeShedule = [{
  firstShift: ["05:45 - 07:00", "07:00 - 08:00", "08:00 - 09:00", "09:00 - 10:00", "10:00 - 11:00", "11:00 - 12:00", "12:00 - 13:00", "13:00 - 14:00", "14:00 - 14:45", ]
}];

buildTable()

function buildTable() {
  $.each(lpmsData, function(i, data) {
    var categoryBuild = '<tr><td width = "150">' + timeShedule[0].firstShift[i] + '</td><td>' + data.item + '</td><td>' + data.actual + '</td><td>' + data.target + '</td><td>' + data.defects + '</td><td>' + data.efficiency + '</td><td>' + data.pefomance + '</td><td>' + data.oee + '</td></tr>';
    if (data.efficiency <= 50) {
      categoryBuild = $($.parseHTML(categoryBuild))
      categoryBuild.css("background-color", "blue");
    }
    $('.tableData').append(categoryBuild);
  });

}
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th></th>
      <th>Item number</th>
      <th>Actual</th>
      <th>Target</th>
      <th>Defects</th>
      <th>Efficiency</th>
      <th>Performance</th>
      <th>OEE</th>
    </tr>
  </thead>
  <tbody class = "tableData">
  </tbody>
</table>

Альтернативный способ сделать это следующим образом:

if (data.efficiency <= 50) {
  categoryBuild = $($.parseHTML(categoryBuild))
  categoryBuild.css("background-color", "blue");
}

@ qunz666 попробуйте посмотреть на второй способ.

Carsten Løvbo Andersen 21.05.2019 08:39

Вы можете использовать литералы шаблонов и добавить класс в tr. <tr class = "${data.efficiency<=50?'blue':''}"> проверяет, меньше ли значение data.efficiency 50 или равно ему. Если это так, класс будет добавлен в tr

var lpmsData = [{
    item: "111000355B",
    order: "9999999999",
    actual: "403",
    target: "404",
    defects: "1",
    efficiency: 89,
    pefomance: 78,
    oee: "N/A",
    startTime: "06:45:44"
  },
  {
    item: "102211549B",
    order: "8888888887",
    actual: "504",
    target: "366",
    defects: "123",
    efficiency: 125,
    pefomance: 96,
    oee: "N/A",
    startTime: "05:35:64"
  },
  {
    item: "112255458C",
    order: "7777777777",
    actual: "777",
    target: "555",
    defects: "1",
    efficiency: 155,
    pefomance: 102,
    oee: "N/A",
    startTime: "07:44:44"
  },
  {
    item: "111225445G",
    order: "6666666666",
    actual: "403",
    target: "404",
    defects: "1",
    efficiency: 34,
    pefomance: 78,
    oee: "N/A",
    startTime: "11:55:09"
  },
  {
    item: "584844455A",
    order: "5555555555",
    actual: "905",
    target: "905",
    defects: "1",
    efficiency: 100,
    pefomance: 78,
    oee: "N/A",
    startTime: "12:45:44"
  },
  {
    item: "111000354B",
    order: "9999999999",
    actual: "403",
    target: "404",
    defects: "1",
    efficiency: 89,
    pefomance: 78,
    oee: "N/A",
    startTime: "13:45:44"
  },
  {
    item: "102253212B",
    order: "8888888887",
    actual: "504",
    target: "366",
    defects: "123",
    efficiency: 125,
    pefomance: 96,
    oee: "N/A",
    startTime: "13:55:44"
  },
  {
    item: "112241678C",
    order: "7777777777",
    actual: "777",
    target: "555",
    defects: "1",
    efficiency: 50,
    pefomance: 102,
    oee: "N/A",
    startTime: "14:15:44"
  },
  {
    item: "111225456G",
    order: "6666666666",
    actual: "403",
    target: "404",
    defects: "1",
    efficiency: 89,
    pefomance: 78,
    oee: "N/A",
    startTime: "14:22:46"
  },
  {
    item: "584844000A",
    order: "5555555555",
    actual: "905",
    target: "905",
    defects: "1",
    efficiency: 100,
    pefomance: 78,
    oee: "N/A",
    startTime: "14:36:13"
  }
];

var timeShedule = [{
  firstShift: ["05:45 - 07:00", "07:00 - 08:00", "08:00 - 09:00", "09:00 - 10:00", "10:00 - 11:00", "11:00 - 12:00", "12:00 - 13:00", "13:00 - 14:00", "14:00 - 14:45", ]
}];

function buildTable() {
  $.each(lpmsData, function(i, data) {
    var categoryBuild = `<tr class=${data.efficiency<=50?"blue":""}>
    <td width = "150">${timeShedule[0].firstShift[i]}</td>
    <td>${data.item}</td>
    <td>${data.actual}</td> 
    <td>${data.target}</td>
    <td>${data.defects}</td>
    <td>${data.efficiency}</td>
    <td>${data.pefomance}</td>
    <td>$data.oee}</td>
    </tr>`;

    $('.tableData').append(categoryBuild);
  });

}
buildTable()
.blue {
  background: blue;
  color: white;
}
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th></th>
      <th>Item number</th>
      <th>Actual</th>
      <th>Target</th>
      <th>Defects</th>
      <th>Efficiency</th>
      <th>Performance</th>
      <th>OEE</th>
    </tr>
  </thead>
  <tbody class = "tableData">
  </tbody>
</table>

Почему не просто чистый CSS?

 tbody.tableData tr:nth-child(even) {background: red;}

Другие вопросы по теме