通过jQuery为未来创建的元素添加CSS规则 [英] Add CSS rule via jQuery for future created elements
问题描述
我有一个不寻常的问题。我做了很多次这样的事情:
I have a somewhat unusual issue. I've done something like this many times:
$('#selector').css('color','#00f');
$ b < > ,我调用上面的命令,它工作正常。
My problem is that I create a <div id="selector">
, and I call the command above and it works fine.
现在,在另一个事件, DOM ,并在以后使用相同的ID重新添加。此元素现在没有 color:#00f
。
Now, on another event, later, I remove that element from the DOM and add it again at a later time with the same id. This element now doesn't have color:#00f
.
有一种方法可以添加规则在CSS中,以便它将影响以后创建的项目与 id
/ 类
?我喜欢 jQuery ,但是使用纯JavaScript的任何东西都会很好。
Is there a way that I can add a rule in CSS, such that it will affect items that are created in the future with that same id
/class
? I like jQuery, but anything with plain JavaScript would be fine as well.
它必须是动态的,我不知道放在CSS文件中的类。此外,我计划在应用程序的过程中更改单个属性几个不同的时间。例如,将颜色设置为
黑色
,将蓝色
, red
,并返回 black
。
It has to be dynamic, and I don't know the classes to put in a CSS file. Also, I plan on changing a single attribute a few different times through the course of the application. For example, setting the color
to black
, to blue
, to red
, and back to black
.
我使用 @lucassp 的答案,这是我最终得到:
I went with the answer from @lucassp, and this is what I ended up with:
function toggleIcon(elem, classname)
{
if($(elem).attr('src')=='img/checkbox_checked.gif')
{
$(elem).attr('src', 'img/checkbox_unchecked.gif')
//$('.'+classname).hide();//this was the old line that I removed
$('html > head').append($('<style>.'+classname+' { display:none; }</style>'));
}
else
{
$(elem).attr('src', 'img/checkbox_checked.gif')
//$('.'+classname).show();//this was the old line that I removed
$('html > head').append($('<style>.'+classname+' { display:block; }</style>'));
}
}
我也想说 @Nelson 可能是最正确的,虽然它需要更多的工作去应用程序代码,总是工作正常,这不是我现在想花费的努力。
I also want to say that @Nelson is probably the most "correct", though it would require more work to go into application code that always works fine, and that's not effort I want to spend at the moment.
如果我以后不得不重写这个(或写类似的东西),我会看看 detach()
。
If I had to rewrite this (or write something similar) in the future, I would look into detach()
.
推荐答案
这应该可以工作:
var style = $('<style>.class { background-color: blue; }</style>');
$('html > head').append(style);
这篇关于通过jQuery为未来创建的元素添加CSS规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!