【发布时间】:2017-06-14 10:57:56
【问题描述】:
我有以下示例代码:
<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.) 如何在每次发布到数据库后刷新数据表,而无需刷新整个窗口/页面?
【问题讨论】:
-
首先,您在
#table选择器$('#myTable).on('change',function(){的末尾缺少单引号,这将导致浏览器控制台中出现语法错误。 -
为什么 OP 以外的其他人更改了源代码....
-
@NewToJS 这只是我的错字。整个代码检查没有浏览器错误。上面的代码是我的代码中的一个 sn-p,所以它可能是我忘记添加的封闭单引号。
-
@NewToJS,同意,整个编辑只是为了插入单引号
'...?它没有任何意义。它可能是问题的原因,更可能只是 OP 很清楚的错字。 -
我理解有时人们在将源代码添加到问题中时会犯错误,但其他人更改它纯粹是基于他们的假设。除非 OP 指出真正的错误或显示相关信息有困难,否则不应更改/更正源代码。
标签: javascript jquery json ajax datatable