我是一個JavaScript和JQuery的新手,所以我在編寫乾淨有組織的代碼時遇到了很多麻煩。下面的代碼只是感覺馬虎,我知道它是。以下是我的代碼的樣例。如果任何人有關於如何通過函數,對象,類來改進它的建議或評論,那將是非常棒的。需要幫助編寫乾淨的有組織的JavaScript代碼
下面的代碼使用一個DataTable的插件,並且通常將包含所有的代碼爲我的網頁。還有更多的事件處理程序需要編寫等等,但我想首先處理我在寫入之前已寫入的內容。
var plannerTable;
$(function() {
// Initialize datatable object
plannerTable = $('#plannerTable').dataTable
({
"bJQueryUI": true,
"bFilter": true,
"sPaginationType": "full_numbers",
"oLanguage":
{
"sZeroRecords": "Add some tasks to your planner"
},
"aoColumns":
[
{ "bSortable": true, "bSearchable": false }, // task id
{"bSortable": true, "bSearchable": false }, // course
{"bSortable": false, "bSearchable": false }, // Edit
{"iDataSort": 2 }, // due date
null, // task
{"bSortable": false, "bSearchable": false }, // Options
{"bSortable": false, "bSearchable": false} // Delete
]
});
/* Insert Time Filter Controls into datatable */
var filterHtml = [
'<ul id="plannerTable_TimeFilter" class="dataTables_TimeFilter">',
'<li><a href="#">Day</a></li>',
'<li><a href="#">Week</a></li>',
'<li><a href="#">Month</a></li>',
'<li><a href="#">All</a></li>',
'<li><a href="#">Last 30 Days</a></li>',
'</ul>'
]
$('#plannerTable_filter').after(filterHtml.join(''));
var dateFilters = $('#plannerTable_TimeFilter li');
/* setup filter click event */
dateFilters.click(function()
{
var dateFilter = $(this).text().replace(/\s+/g, '');
/* Get tasks by date range */
$.getJSON('/Planner/Planner/GetTasksByDateRange', { 'dateFilter': dateFilter }, function (data)
{
plannerTable.fnClearTable();
$.each(data, function (key, value)
{
var row = createTableRow(value);
/* add row to table */
plannerTable.fnAddTr($(row)[0], true);
});
});
});
/*
* Function: createTableRow
* Purpose: Creates an HTML Row using the html in this function
* Returns: constructed html row
* Inputs: row data object
*/
function createTableRow(value)
{
var date = new Date(parseInt(value.DueDate.substr(6)));
/* convert date to proper format */
/* construct html row */
var row = [
'<tr>',
'<td style="display: none;">' + value.TaskId + '</td>',
'<td class="tag-bg" style="width: 10px;">',
'<span class="tag" style="background-color:' + value.CourseBackgroundColor + '" title="' + value.CoursePrefix + '"> ' + '</span>',
'<span style="display: none;">' + value.CoursePrefix + '</span>',
'</td>',
'<td class="edit">',
'<a href="#"><img src="../../../../Content/Images/Planner/edit-icon.png" /></a>',
'</td>',
'<td class="due-date">' + value.DueDate + '</td>',
'<td class="task-col">' + value.TaskName + '</td>',
'<td class="options">',
'<a class="desc" href="#"><img src="../../../../Content/Images/Planner/desc-off-icon.png" /></a>',
'<a class="alert" href="#"><img src="../../../../Content/Images/Planner/bell-off-icon.png" /></a>',
'</td>',
'<td class="delete">',
'<a href="#"><img src="../../../../Content/Images/Planner/delete-icon.png" /></a>',
'</td>',
'</tr>'
]
return row.join('');
}
});
我不喜歡把html放到我的js中,但是由於數據表的樣式量太大或者一些討厭的服務器端解決方案:( – chobo 2011-02-05 22:46:33