如何将 css 应用于动态 HTML 内容?
how to apply css to dynamic HTML content?
我是 CSS 新手,正在学习。
我的问题是,
如果我的 HTML 内容加载有延迟
可能是因为 ajax 请求,
如果我将 html 响应附加到已加载的 div 标签;
如何将 CSS 应用到内部 HTML。
假设我有 div 标签,
<div class="row">
<div class="col-md-5 col-md-offset-2">
<div id="theTableContainer"></div>
</div>
</div>
如果我尝试在 ID 为 "theTableContainer" 的 div 中加载一个 html,
我会在html追加到div
后,在xhr成功的回调函数中应用css
如下
$("#theTableContainer table tr:gt(0)").each(function(){
$(this).find("td:eq(2)").
css("background-color","#8600e6").
css("color","#F8F8FF").
css("font-weight","bold");
});
有没有更好的方法?
请在下面找到 link 的工作代码。
更好的办法是把你想加的css加类然后用addClass
动态加css。
$("#theTableContainer table tr").each(function(){
$(this).find("td").addClass('background color font-weight');
});
.background {
background-color: red;
}
.color {
color: white;
}
.font-weight {
font-weight: 'bold';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-5 col-md-offset-2">
<div id="theTableContainer">
<table>
<tr>
<td>
example
</td>
</tr>
</table>
</div>
</div>
</div>
您可以随时在 css 中添加样式:
#theTableContainer table tbody tr td:nth-child(3){
background-color: #8600e6;
color: #F8F8FF;
font-weight: bold;
}
已更新fiddle.
另一种方法是基于 grouping the css:
$(this).find("td:eq(2)").css({"background-color": "#8600e6",
"color":"#F8F8FF",
"font-weight":"bold"});
您可以制作一个 class 并包含您想要的所有 CSS 属性:
.active {
background-color: #8600e6;
color: #F8F8FF;
font-weight: bold;
}
并应用它:
$(this).find("td:eq(2)").addClass('active');
我是 CSS 新手,正在学习。
我的问题是,
如果我的 HTML 内容加载有延迟 可能是因为 ajax 请求, 如果我将 html 响应附加到已加载的 div 标签;
如何将 CSS 应用到内部 HTML。
假设我有 div 标签,
<div class="row">
<div class="col-md-5 col-md-offset-2">
<div id="theTableContainer"></div>
</div>
</div>
如果我尝试在 ID 为 "theTableContainer" 的 div 中加载一个 html,
我会在html追加到div
后,在xhr成功的回调函数中应用css如下
$("#theTableContainer table tr:gt(0)").each(function(){
$(this).find("td:eq(2)").
css("background-color","#8600e6").
css("color","#F8F8FF").
css("font-weight","bold");
});
有没有更好的方法?
请在下面找到 link 的工作代码。
更好的办法是把你想加的css加类然后用addClass
动态加css。
$("#theTableContainer table tr").each(function(){
$(this).find("td").addClass('background color font-weight');
});
.background {
background-color: red;
}
.color {
color: white;
}
.font-weight {
font-weight: 'bold';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-5 col-md-offset-2">
<div id="theTableContainer">
<table>
<tr>
<td>
example
</td>
</tr>
</table>
</div>
</div>
</div>
您可以随时在 css 中添加样式:
#theTableContainer table tbody tr td:nth-child(3){
background-color: #8600e6;
color: #F8F8FF;
font-weight: bold;
}
已更新fiddle.
另一种方法是基于 grouping the css:
$(this).find("td:eq(2)").css({"background-color": "#8600e6",
"color":"#F8F8FF",
"font-weight":"bold"});
您可以制作一个 class 并包含您想要的所有 CSS 属性:
.active {
background-color: #8600e6;
color: #F8F8FF;
font-weight: bold;
}
并应用它:
$(this).find("td:eq(2)").addClass('active');