Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

363
Views
cambiar el color de fondo de <td> según el valor dinámico, usando javascript

Me gustaría cambiar el color de fondo del estado de mis sistemas. Por ejemplo, si está en línea, devuelve el color de fondo td verde, fuera de línea, rojo, de lo contrario, naranja. Estoy usando for loop (matriz json dinámica de url), por lo que mis resultados no son estáticos, el sistema podría estar en línea ahora y luego fuera de línea después de una hora. Entonces este es mi código, script:

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function () { $.ajax({ url: 'http://localhost/api/job/', dataType: 'JSON', success: function (data) { for (var i = 0; i < data.length; i++) { $(document).ready(function () { var content = '' data.forEach(item => { content += "<tr><td class='" + item.system_status.toLowerCase() + "'>" + item.system_status + "</td></tr>" if (item.system_status.toLowerCase().indexOf('online') === 0) { } else if (item.system_status.toLowerCase().indexOf('offline') === 0) { } else if (item.system_status.toLowerCase().indexOf('down') === 0) { } }) $('#table_body').html(content); }) } } }); }); </script>

y este es mi html:

 <style> td.online { background-color: #a4bc31; } td.offline { background-color: #bc3131; } td.down { background-color: yellow; } </style> </body> <table> <tbody id='table_body'></tbody> </table>

¿¿que estoy haciendo mal??

y sigue igual, solo se colorea el online y el offline.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Puede probar el siguiente método para agregar background-color a las celdas que contienen el estado del sistema.

Agregue un nombre de clase a la celda mientras lo agrega a DOM y cambie el color de fondo usando el mismo nombre de clase.

 $(document).ready(function () { $.ajax({ url: "http://localhost/api/job/", dataType: "JSON", success: function (data) { for (var i = 0; i < data.length; i++) { $(document).ready(function () { var content = ""; data.forEach((item) => { var class_name = ""; if (item.system_status.toLowerCase().indexOf("online") === 0) { class_name = "online"; } else if ( item.system_status.toLowerCase().indexOf("offline") === 0 ) { class_name = "offline"; } else if (item.system_status.toLowerCase().indexOf("down") === 0) { class_name = "down"; } content += "<tr><td class='" + class_name + "'>" + item.system_status + "</td></tr>"; }); $("#table_body").html(content); }); } }, }); });
 table, td { border: 1px solid #ddd; border-collapse: collapse; } td.online, td.offline, td.down { color: #fff; } td.online { background-color: green; } td.offline { background-color: orange; } td.down { background-color: red; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <table> <tbody id='table_body'></tbody> </table>

EDITAR

Ha actualizado el HTML de la forma en que se recibe la respuesta y se actualiza el DOM.

EDITAR-2

He agregado otra matriz llamada status . Una vez que reciba los datos de respuesta de la API, puede verificar el estado recibido con la matriz de status , de la siguiente manera:

 status[data.system_status]

Entonces devolverá el nombre de clase correspondiente.

EDITAR-3

Dado que hay muchas posibilidades de que un estado pueda ser, estamos planeando una condición if-else , de la siguiente manera:

 if(data.system_status.toLowerCase().indexOf('online') === 0) { // Add class 'online' to the cell } else if(data.system_status.toLowerCase().indexOf('offline') === 0) { // Add class 'offline' to the cell } else if(data.system_status.toLowerCase().indexOf('down') === 0) { // Add class 'down' to the cell }

EDITAR-4

Se actualizó la respuesta según la actualización en el fragmento de pregunta

about 4 years ago · Juan Pablo Isaza Report

0

Realmente no sé cómo se podría escribir esta lógica en Django, pero lo intenté a continuación. A ver si esto ayuda.

 <table> <tr> <th> System Name </th> <th> System Status</th> </tr> </tr> {% for i in response %} {% if i.system_status == 'ONLINE' %} {% bgcolor = 'green' %} {% elif i.system_status == 'OFFLINE' %} {% bgcolor = 'red' %} {% else %} {% bgcolor = 'orange' %} {% endif %} <tr> <td> {{ i.system_name }}</td> <td style="background:{{ bgcolor }}"> {{ i.system_status }}</td> </tr> {% endfor %} </table>
about 4 years ago · Juan Pablo Isaza Report

0

Estoy de acuerdo con los otros usuarios en que sería más fácil para usted agregar información de clase a la celda en PHP, pero si desea agregar las clases a la celda de estado después de que se haya renderizado la página, puede usar JS nativo para iterar sobre el filas

 // Cache the rows in the table body const rows = document.querySelectorAll('tbody tr'); // Iterate over them rows.forEach(row => { // Grab the second cell (status) const status = Array.from(row.querySelectorAll('td'))[1]; // And depending on the text content add // the appropriate class to the cell switch(status.textContent) { case 'Online': status.classList.add('online'); break; case 'Offline': status.classList.add('offline'); break; default: status.classList.add('other'); break; } });
 .online { background-color: green; } .offline { background-color: red; } .other { background-color: orange };
 <table> <thead> <tr><th>System Name</th><th>System Status</th></tr> </thead> <tbody> <tr><td>Bob</td><td>Online</td></tr> <tr><td>Sally</td><td>Offline</td></tr> <tr><td>Steve</td><td>Billy Joel</td></tr> </tbody> </table>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!