简体   繁体   English

jQuery-更改未创建的div元素的样式

[英]jQuery - change style of uncreated div elements

I was trying to searchengine for this, but I'm not sure how to call it exactly. 我试图为此搜索引擎 ,但是我不确定如何准确地称呼它。

I can change the style of my div elements successfuly, for example: 我可以成功更改div元素的样式,例如:

$(document).ready($('div.element1').css("float", "left"));

This will successfully change all the elements of class element1 that exist. 这将成功更改类element1中存在的所有元素。 However, the new (after above is executed) elements will still spawn with old option of float: right; 但是,新的(在执行完之后)元素仍将使用旧的float: right;选项生成float: right; . What is my best/simplest option for permanently changing the style of this div ? 永久更改此div样式的最佳/最简单选择是什么? I can inject it manually after the element is created but that feels wrong to be honest. 创建元素后,我可以手动注入它,但是说实话,这感觉是错误的。

It is better if you don't add inline style using .css() method, but instead just add/remove classes having your style, so create a class for all those elements' style. 最好不要使用.css()方法添加内联样式,而只需添加/删除具有您的样式的类,因此为所有这些元素的样式创建一个类。

If the newly created elements have the class you define, then they will have the style too. 如果新创建的元素具有您定义的类,那么它们也将具有样式。

Optionally, you can do this: 您可以选择执行以下操作:

$(document).on('change or_other_event','your_selectors', function(){
   // your code
});

If the new elements have classes element1 , element2 ..., you would need something like this: 如果新元素的类为element1element2 ...,则将需要以下内容:

$(document).on('change','div[class*="element"]', function(){
   // your code
});

Just create a new class on your css and then add that class to your new element 只需在CSS上创建一个新类,然后将该类添加到新元素中

.newElement{
 color:red//example style
}

$("<div>",{class:'newElement'})

Your code: 您的代码:

$(document).ready($('div.element1').css("float", "left"));

is equivalent to: 等效于:

var element = $('div.element1').css("float", "left");
$(document).ready(element);

This means any un-drawn elements will not be affected. 这意味着任何未绘制的元素都不会受到影响。 Instead use: 而是使用:

$(document).ready(function() {
   $('div.element1').css("float", "left");
});

The above code ensures changes are made once the page has loaded. 上面的代码确保页面加载后进行更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM