如何将css类应用于" td"根据条件?请检查以下代码。我有一个名为" FunctionArea"我需要动态创建td并根据条件
应用CSS
var tbody = $('#FunctionArea tbody');
var FArea = ['test','test1','test2','test3'];
$.each(FArea, function (i, FArea) {
var tr = $('<tr>')
$('<td>').html(FArea).appendTo(tr);
$.each(FunctionArea, function (i, FunctionArea) {
if (FArea == FunctionArea.split(':')[0])
{
var tdclass = FunctionArea.split(':')[3] == "Input" ? 'input' : 'delivarable';
$('<td>').addClass(tdclass);
$('<td>').html("<a class='hiddenTab' href=" + FunctionArea.split(':')[2] + ">" + FunctionArea.split(':')[1] + "</a>").appendTo(tr);
}
});
tbody.append(tr);
});
&#13;
table#FunctionArea {
border-collapse: separate;
border-spacing: 15px;
color: #4a4a4d;
font: 14px/1.4 "Helvetica Neue", Helvetica, Arial, sans-serif;
margin: 10px;
border: 1px solid #ddd;
}
#FunctionArea th,
table.input td {
background-color: #4CAF50;
border: none;
color: white;
padding: 7px 13px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 12px;
margin: 3px 3px;
cursor: pointer;
/*-webkit-transition-duration: 0.4s;*/
transition-duration: 0.4s;
border-radius: 8px;
}
table.delivarable td {
background-color: yellow;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head></head>
<body>
<table id="FunctionArea">
<tbody></tbody>
</table>
</body>
</html>
&#13;
答案 0 :(得分:0)
建议使用&#34; $()。html()&#34;来避免直接dom操作。 因为不创建有用的对象。 而是创建对象并追加。
`
<table id="myTable">
</table>
<button id="btAppend">Append</button>
<style>
.blue{ color:blue;}
.red{ color:red;}
</style>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
var counter=0;
var myTable=$("#myTable");
var btAppend=$("#btAppend");
btAppend.click(function(){
counter++;
var tr=$('<tr id="id-mytr-'+counter+'">');
var td1=$('<td>');
var tdclass=(counter % 2 == 1)?"blue":"red";
td1.addClass(tdclass);
td1.append("Hello");
tr.append(td1);
myTable.append(tr);
});
</script>
`