首页 > 解决方案 > 如何使用 CSS 编辑 jQuery 表格

问题描述

我有一个使用 jQuery 创建表的外部文件。我正在尝试将第一列设置为与其他列不同的宽度。我更愿意添加一些我可以在 css 中使用的东西,以使将来的编辑更容易。我正在努力使语法正确。我的一些尝试显示在代码注释中,但我尝试了其他尝试,但也失败了。

var $table = $('<table>');
$table.append()
// thead
.append('<thead>').children('thead')
.append('<tr />').children('tr').append('<th></th><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th>');

//tbody
var $tbody = $table.append('<tbody />').children('tbody');

// add row
$tbody.append('<tr />').children('tr:last')
//.append("<th class="dynamicTable-rowHead">name</td>") -console gives Uncaught SyntaxError: missing ) after argument list
//.append("<th>name</th>").setAttribute('width', '10%')  //setAttribute is not a function
.append("<th>name</td>")  //this works but cannot define a width in css without it affecting all table columns
.append("<td>val</td>")
.append("<td>val</td>")
.append("<td>val</td>")
.append("<td>val</td>")
.append("<td>val</td>")
.append("<td>val</td>")
.append("<td>val</td>");

// add table to dom
$table.appendTo('#dynamicTable');

标签: jquerycsshtml-table

解决方案


您只能使用 css 来完成。

var $table = $('<table>');
$table.append()
// thead
.append('<thead>').children('thead')
.append('<tr />').children('tr').append('<th></th><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th>');

//tbody
var $tbody = $table.append('<tbody />').children('tbody');

// add row
$tbody.append('<tr />').children('tr:last')
//.append("<th class="dynamicTable-rowHead">name</td>") -console gives Uncaught SyntaxError: missing ) after argument list
//.append("<th>name</th>").setAttribute('width', '10%')  //setAttribute is not a function
.append("<th>name</td>")  //this works but cannot define a width in css without it affecting all table columns
.append("<td>val</td>")
.append("<td>val</td>")
.append("<td>val</td>")
.append("<td>val</td>")
.append("<td>val</td>")
.append("<td>val</td>")
.append("<td>val</td>");

// add table to dom
$table.appendTo('#dynamicTable');
#dynamicTable th:first-child{
  width:200px;
}

#dynamicTable th{
  width:100px;
  text-align:left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dynamicTable"></div>


推荐阅读