将样式从CSS应用到新添加的元素 [英] Applying styles from CSS to newly appended elements
问题描述
$('。some_div')。append(<在我的CSS中,我们可以使用一个简单的例子来说明如何使用CSS来创建一个简单的CSS文件,
.hi {
颜色:白色;
}
然而,既然< li class =hi >
是动态添加的,看起来CSS中定义的样式不适用于元素。所以,
$('。some_div')。append(< li class ='hi'> hey!< ; / li>)
$('li.hi')。css({color:white});
实际上可以做到这一点,但对我来说似乎是多余的,因为样式已经在CSS文件中定义。这是唯一的方法吗?
更新:
$('。some_div')。append('< li style =color:white> hey!< / li>)
以上内容可以工作,但由于样式已经在单独的CSS文件中定义,所以它仍然是多余的。我的问题是,是否有办法避免这种冗余。
在CSS中,
.some_div> li {
font-size:20px;
background-color:30px;
margin-right:2px;
}
.hi {
颜色:白色;
}
所有这些都不会在我通过($)。append()
,所以我问是否有一种方法可以应用样式表中已经定义的样式,而无需在样式表中重新定义样式 css()
函数。
解决方案您需要在此处转义类名称。
更改
$('。some_div')。append(< li class =hi> hey!<李>中);
至
$('。some_div')。append(< li class ='hi'> hey!< / li>);
OR
$('。some_div')。append(< li class = \hi \> hey!< / li>);
演示样式:
<$ p $ (< / li>>< code> $('。some_div')。append(< li style ='color:green;'> hey!< / li>);
OR
$( 'some_div。')附加( <李>哎LT; /立GT;!)找到。( 利:最后一个)的CSS( 颜色, 黄色);
I add an element to a parent div dynamically.
$('.some_div').append("<li class="hi">hey!</li>")
In my CSS,
.hi {
color: white;
}
However, since <li class="hi">
is dynamically added, it seems the styles defined in CSS are not applied to the element. So,
$('.some_div').append("<li class='hi'>hey!</li>")
$('li.hi').css({"color":"white"});
would actually do the trick, but it seems redundant to me as the style is already defined in CSS file. Is this the only way to do it?
Update:
$('.some_div').append('<li style="color:white" >hey!</li>')
The above will work, but since the style is already defined in a separate CSS file, it'd be still redundant. My question was if there is a way to avoid this redundancy.
in CSS,
.some_div > li {
font-size: 20px;
background-color: 30px;
margin-right: 2px;
}
.hi {
color: white;
}
All of this won't be applied when I add a new element via ($).append()
, so I am asking if there is a way to apply the styles that are already defined in a stylesheet, without having to re-defining them in a css()
function.
You need to escape name of class here.
Change
$('.some_div').append("<li class="hi">hey!</li>");
to
$('.some_div').append("<li class='hi'>hey!</li>");
OR
$('.some_div').append("<li class=\"hi\">hey!</li>");
Demo with style:
$('.some_div').append("<li style='color:green;'>hey!</li>");
OR
$('.some_div').append("<li>hey!</li>").find("li:last").css("color","yellow");
这篇关于将样式从CSS应用到新添加的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!