Изменение цвета <tr> в jQuery Laravel
Куда я должен поставить, если в jQuery
изменить цвет? если я комментирую логическое IF, данные отображаются нормально.
Вот этот код
$('.tbody-reply').empty();
if(data != ""){
data.forEach(element => {
$('.tbody-reply').append( ""+
"<tr>" +
"<td>" + element.description + "</td>" +
"<td>" + element.created_at + "</td>" +
"</tr>");
// if(element.idResponder == 'TE')
// $('#').css("background-color", "yellow");
});
}else{
$('.tbody-reply').append( ""+
"<tr>" +
"<td align='center' colspan='6'>No Data Found</td>" +
"</tr>");
}
У вопроса есть решение - Посмотреть?
Ответы - Изменение цвета <tr> в jQuery Laravel / Change <tr> color in jQuery Laravel

29.09.2020 11:12:12
Создания объекта строки вместо добавления в код HTML строка. Затем условно измените этот объект и добавьте его
const $tr = $(
"<tr>" +
"<td>" + element.description + "</td>" +
"<td>" + element.created_at + "</td>" +
"</tr>"
)
if (element.idResponder == 'TE') {
$tr.css("background-color", "yellow")
}
$('.tbody-reply').append($tr);

29.09.2020 11:16:00
если я правильно вас понял, вы хотите раскрасить ячейку, когда это условие будет выполнено. переменная данных-это массив? если это массив, то вы неправильно проверяете пустоту. правильный вариант:
if(data.length !== 0){
data.forEach(element => {
let parent = $('.tbody-reply');
parent.append( ""+
"<tr>" +
"<td>" + element.description + "</td>" +
"<td>" + element.created_at + "</td>" +
"</tr>");
if(element.idResponder == 'TE')
parent.css("background-color", "yellow");
});
}else{
$('.tbody-reply').append( ""+
"<tr>" +
"<td align='center' colspan='6'>No Data Found</td>" +
"</tr>");
}
Является ответом!

29.09.2020 11:22:14
Вы можете применить CSS
к строкам при создании нового td
в вашей функции loop
. У меня также есть cleaned
, как вы создавали элементы td
.
if (response.length) {
response.forEach(element => {
let row = $('<tr>'); //create row
if (element.idResponder == 'TE') { //check if TE
row.append($('<td>').html(element.description));
row.append($('<td>').html(element.created_at));
row.css("background-color", "yellow"); //apply css
} else {
row.append($('<td>').html(element.description));
row.append($('<td>').html(element.created_at));
}
table.append(row) //append all data
});
} else {
let row = $('<tr>');
table.append(row)
row.append($('<td align="center" colspan="6">').html('No Data Found'));
}
Рабочая Демонстрация:
var response = [{
"description": "Always Helping",
"created_at": "03-02-2002",
'idResponder': 'TE'
}, {
"description": "Foo",
"created_at": "03-02-2020",
'idResponder': 'Foo'
}, {
"description": "Ikra",
"created_at": "03-02-2020",
'idResponder': 'TE'
}]
let table = $('.tbody-reply')
if (response.length) {
response.forEach(element => {
let row = $('<tr>');
if (element.idResponder == 'TE') {
row.append($('<td>').html(element.description));
row.append($('<td>').html(element.created_at));
row.css("background-color", "yellow"); //apply css
} else {
row.append($('<td>').html(element.description));
row.append($('<td>').html(element.created_at));
}
table.append(row) //append all data
});
} else {
let row = $('<tr>');
table.append(row)
row.append($('<td align="center" colspan="6">').html('No Data Found'));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Created Date</th>
</tr>
</thead>
<tbody id="tdata" class="tbody-reply">
</tbody>
</table>

29.09.2020 04:30:08
Один из подходов заключается в следующем:
// dummy data for the example to work with:
const data = [{
'description': 'something',
'created_at': Date.now(),
'idResponder': 'TE'
}, {
'description': 'other',
'created_at': Date.now(),
'idResponder': 'TIE'
}, {
'description': 'than',
'created_at': Date.now(),
'idResponder': 'THE'
}, {
'description': 'the',
'created_at': Date.now(),
'idResponder': 'TEN'
}, {
'description': 'previous',
'created_at': Date.now(),
'idResponder': 'TE'
}, {
'description': 'entry',
'created_at': Date.now(),
'idResponder': 'TEPID'
}];
// caching a reference to the <tbody class="tbody-reply"> element:
const $tbody = $('tbody.tbody-reply');
// emptying out that element:
$('.tbody-reply').empty();
if (data != "") {
// iterating over the Array of Objects using Array.prototype.forEach():
data.forEach(
// with an Arrow function, which passes a reference to the current
// Object - of the Array of Objects - to the inner body of the
// function:
(datum) => {
// here we know the names of the properties we wish to work with, so
// we can use destructuring to assign those properties to variables
// within the function block:
let {
description,
created_at,
idResponder
} = datum,
// here we use a template literal (delimited with back-ticks) to create
// the <tr> element, and its children; we use a conditional operator
// to test if the idResponder variable is equal to 'TE', if it is we
// return a class-name of 'highlight', and if not we return an empty
// String:
tr = `<tr ${ idResponder === 'TE' ? 'class="highlight"' : '' }">
<td>${description}</td>
<td>${created_at}</td>
</tr>`
// we then append the created <tr> to the cached <tbody> element:
$tbody.append(tr);
});
} else {
$tbody.append(`
<tr>
<!-- because you didn't post your relevant HTML, or a sample of your
Array of Objects I couldn't recreate your whole <table> so I only
created two <td> elements per row; this colspan attribute will
of course need to be changed back to 6 for your own use -->
<td align="center" colspan="2">No Data Found</td>
</tr>`);
}
*,
::before,
::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
table {
border-collapse: collapse;
width: 80vw;
margin: 1em auto;
border: 3px solid #aaa;
}
th {
border-bottom: 2px solid #aaa;
}
tr.highlight {
background-color: #ffa;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Description:</th>
<th>Created at:</th>
</tr>
</thead>
<tbody class="tbody-reply">
</tbody>
</table>
Рекомендации:
- Функции стрелок.
Array.prototype.forEach()
.Date.now()
.- Заданиена разрушение .
- Шаблонные литералы.
Помочь в развитии проекта: