我有下面的示例代码:
<table id='myTable'>
<tr>
<td>Id</td>
<td>Status</td>
<td>Summary</td>
</tr>
</table>
//Sample document ready function
$(document).ready(function(){
$('#myTable').dataTable({
"aoColumnDefs": [
{
"aTargets":[1],
"createdCell": function (td, cellData, rowData, row, col){
if(cellData === 'ordered')
$(td).css('background-color', '#5cb85c');
if(cellData === 'not_ordered')
$(td).css('background-color', '#d9534f');
if(cellData === 'shipped')
$(td).css('background-color', '#f0ad4e');
}
},
{
"aTarget": [2],
"render": function(data, type, full, meta){
if(type === 'display' && data == null) {
data = "enter field summary";
return '<input type="text"' + data +'>';
}
else
return '<input type="text"' + data + '>';
}
}
]
});
//With this function, i want to change the background-color of select field per option selected.However, the val() is returning "undefined"
$('#myTable').on('change',function(){
var optionField = $(this).closest('tr').find('option:selected').val();
if(optionField === 'ordered')
$(this).css({'background-color':'#696969'});
else if(optionField === 'notOrdered')
$(this).css({'background-color':'#e7e7e7'});
else(optionField === 'shipped')
$(this).css({'background-color':'#326f3a'});
}
$('table').on('click', 'input[type="submit"]', function(e)){
var url = 'hiddenAPI.com';
$.ajax({
url: url,
type: "POST",
async: true,
data: {
id: idField,
status: statusField,
summary: summaryField
},
dataType: "json",
success: function (data){
$('#responseField').html('Order ' + idField + ', summary has been posted to the database successfully');
$('#myTable').ajax.reload(); //<- table not refreshing here
},
});
});
});
使用上面的代码,我想在每次选择选择选项时更改背景颜色(根据上面的代码中的值确定(,并且在每次发布到数据库之后,我想使用新的 JSON 数据刷新整个数据表。到目前为止,数据表站点(table.ajax.reload(((上提供的API不起作用。
两个问题,
1.(使用上面的代码,选择选择选项后如何更改数据表中特定列的背景颜色?
2.( 如何在每次发布到数据库后刷新数据表,而不必刷新整个窗口/页面?
在这里:
$(this).css({background-color':'#696969'});
else if(optionField === 'notOrdered')
$(this).css({background-color':'#e7e7e7'});
else(optionField === 'shipped')
$(this).css({background-color':'#326f3a'});
}
"背景颜色"字符串在开头缺少一个额外的 '
编辑:抱歉,仅修复了语法错误
玩了一会儿,我最终自己解决了这个问题。1.( 为了刷新 ajax 数据,我最终在 done 函数中调用了另一个 ajax 调用(来自另一个主要函数(。
2.( 要单击并返回表格行中最接近的选定选项,我最终首先在表上创建了一个单击函数,然后嵌套了另一个函数用于更改时选择,然后使用 $(this(.closest('tr(.find('select'(.val((。