Javascript / HTML / CSS
我正在构建一个动态表,并尝试根据返回的数据来设置特定单元格的样式。这样做的理由是,我需要用户知道某些单元格是“可单击的”链接,这些链接可捕获值并在单击时发出附加的AJAX请求。我遇到的问题是样式更改已成功应用于除最后一行以外的每一行。我已经遍历了代码,并且正在最后一行数据中点击该行代码。此外,查看DOM资源管理器,每个单元格都应用了样式,最后一行为空。发生魔术的代码行是
var firstCol = table.rows [i] .cells [0];
对此将提供任何帮助!
<html>
<head>
<style>
/* CSS */
.cellStyle{
cursor: default;
pointer-events: none;
text-decoration: none;
}
</style>
</head>
<body>
<div id="main">
<div id="showData"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
var controllerURL = '/DataCall/GetData';
$.ajax({
type: "GET",
url: controllerURL,
data: param = "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data) {
// THE ARRAY TO STORE JSON ITEMS.
var arrItems = [];
// PUSH THE VALUES INSIDE THE ARRAY.
$.each(data, function (index, value) {
arrItems.push(value);
});
// EXTRACT VALUE FOR TABLE HEADER.
var col = [];
for (var i = 0; i < arrItems.length; i++) {
for (var key in arrItems[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
// TABLE ROW.
var tr = table.insertRow(-1);
// TABLE HEADER.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");
th.innerHTML = col[i];
tr.appendChild(th);
}
if (col.length == 2) {
for (var i = 0; i < arrItems.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = arrItems[i][col[j]];
// REMOVES DEFAULT FORMATTING FOR FIRST COLUMN
var firstCol = table.rows[i].cells[0];
firstCol.className = 'cellStyle';
tabCell.addEventListener("click", (function () {
// ASSIGN CLICKED VALUE TO VARIABLE
var clickedValue = this.innerHTML;
// PASS THE CLICKED VALUE TO DataCallController
var getTableInfoControllerURL = '/DataCall/GetTableInfo'
if (col.length == 2 && clickedValue != arrItems[0][col[0]]) {
$.ajax({
type: "POST",
url: getTableInfoControllerURL,
data: { "dbName": arrItems[0][col[0]], "tblName": clickedValue },
dataType: "json",
error: errorFunc
});
}
else if (col.length == 2 && clickedValue == arrItems[0][col[0]]) {
$.ajax({
type: "POST",
url: getTableControllerURL,
data: { "dbName": clickedValue },
dataType: "json",
error: errorFunc
});
}
function errorFunc() {
alert('Failed');
}
}));
}
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
</body>
</html>