向字符串表添加样式不起作用

时间:2019-07-02 05:58:32

标签: jquery html css

我在jquery调用中有如下字符串HTML

var template = '<html >' +

'<head>' +
'<h1>Most important heading here</h1>'+

'</head>' +
'<body>' +

'<table border="2px" class="ExlTable"><tr bgcolor="#87AFC6">{table}</table>' +

'</body></html>';

我正在将现有表数据加载到此{table}

我要设置此表的大小,我正在使用

$('th').css('width', '200');
$('th').css('height', '30');
$('td').css('height', '30');

这是有效的,但是会影响页面上的所有表格,因此我尝试了以下两种类型,但是没有起作用

$('.ExlTable th').css('width', '200');
$('.ExlTable th').css('height', '30');
$('.ExlTable td').css('height', '30');

不起作用

var $template = $(template);
$template.find('th').css('width', '200');
$template.find('th').css('height', '30');
$template.find('td').css('height', '30');

不起作用,请帮助

4 个答案:

答案 0 :(得分:2)

template对此不包含任何theadth,因此这就是您的代码“无效”的原因。

我已将theadth添加到您的代码中,然后一切正常。

var template = '<html >' +

'<head>' +
'<h1>Most important heading here</h1>'+

'</head>' +
'<body>' +

'<table border="2px" class="ExlTable"><thead><tr><th>TableHeader</th></tr></thead><tbody><tr bgcolor="#87AFC6"><td>{table}</td></tbody></table>' +

'</body></html>';

var $template = $(template);
$template.find('th').css('width', '200');
$template.find('th').css('height', '30');
$template.find('td').css('height', '30');

$(".tableContainer").html($template)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tableContainer"></div>

答案 1 :(得分:0)

使用老式的CSS:

<style>
.ExlTable th {
    width:200px;
    height:30px;
}
.ExlTable td {
    height:30px;
}
</style>

确保已正确设置{table}变量中的表内容

答案 2 :(得分:0)

您必须将宽度/高度指定为百分比或px之类的特定度量

例如:

var $template = $(template);
$template.find('th').css('width', '200px');
$template.find('th').css('height', '30px');
$template.find('td').css('height', '30px');

var $template = $(template);
$template.find('th').css('width', '50%');
$template.find('th').css('height', '30%');
$template.find('td').css('height', '20%');

答案 3 :(得分:0)

您缺少td,但这可能会对您有所帮助。

$("#test").html(template);
$("#test").find('th').css('width', '200');
$("#test").find('th').css('height', '30');
$("#test").find('td').css('height', '30');

Click Here