jQuery CSS:动态地更改类的属性 [英] jQuery CSS: Dynamically change attributes of a class

查看:239
本文介绍了jQuery CSS:动态地更改类的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改一个类的属性,在该类上所有使用该类的元素将用于Web应用程序生命的其余部分(从开始使用直到用户退出Web应用程序)。



html:

 < p class =myClass> 
是什么?
< / p>
< p class =myClass>
现在?
< / p>

css:

 code> .myClass {
background-color:#ffff00;
}

js:

  $(。myClass)。css(background-color,#00FFFF); 
$(p)。last()。after(< div class ='myClass'> Now!< / div>);

这里示例



我想从示例中实现的是,所有后续动态添加的myClass将具有新属性。从jsFiddle中,您将看到下一个添加的元素没有新属性。



更多: b
$ b

我只是使用颜色作为基础,我将实现这个在更大的规模,我想实现是动态改变一个类的属性将被用于整个

解决方案

使用css()方法更改现有元素的内联样式,使用它来更改未来元素的样式。一个解决方法(我不太喜欢)是插入一个样式标签:

  $(< style> ; .myClass {background-color:#00FFFF}< / style>).appendTo(head)
$(p)。last()。after(< div class ='myClass '> Now!< / div>);

FIDDLE


I want to change the attribute of a class on which all element that use the class for the rest of the web application life (from start of use until the user exits the web application) will be affected.

html:

<p class="myClass">
    What?
</p>
<p class="myClass">
    Now?
</p>

css:

.myClass{
    background-color: #ffff00;    
}

js:

$(".myClass").css("background-color", "#00FFFF");
$("p").last().after("<div class='myClass'>Now!</div>");

Here is a sample

What I want to achieve from the sample is that all subsequent dynamically added myClass will have the new attribute. From the jsFiddle, you'll see that the next added element doesn't have the new attribute.

MORE:

I'm just using the color for a basis, I will implement this in larger scale, what I want to accomplish is to dynamically change the attributes of a class that will be used for the entire web app life cycle.

解决方案

Using the css() method changes the inline styles on already existing elements, and you can't use that to change the styles on future elements. A workaround (that I don't like very much) would be to insert a style tag:

$( "<style>.myClass {background-color : #00FFFF}</style>" ).appendTo( "head" )
$("p").last().after("<div class='myClass'>Now!</div>");

FIDDLE

这篇关于jQuery CSS:动态地更改类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆