[英]Apply CSS to dynamically generated elements
I am trying to work out how to call my .each() function with a $(document).ready and a click event, at the moment I have this 我正在尝试找出如何使用$(document).ready和click事件调用.each()函数,此刻
$(document).ready(function(){
$(".help-inline").each(function() {
$(this).css('display', 'none');
});
});
Within a form of mine using nested_form I can clone a field clicking '.example_button' and would like to apply the display:none rule to the newly created element within my DOM. 在我的使用nested_form的表单中,我可以克隆一个单击“ .example_button”的字段,并希望将display:none规则应用于DOM中新创建的元素。
I have tried this, but obviously the rule is only applied when i click the '.examnple_button' 我已经尝试过了,但是很明显,该规则仅在单击“ .examnple_button”时适用
$(document).on('click', '.example_button', function(){
$(".help-inline").each(function() {
$(this).css('display', 'none');
});
});
How can i apply the css rules under both circumstance? 在这两种情况下如何应用CSS规则?
Thanks 谢谢
You can try this : 您可以尝试以下方法:
$(document).on('focus', '.example_button', function(){
$(".help-inline").css('display', 'none'); //or $(".help-inline").hide();
});
The .each()
which you are using to iterate '.help-inline'
is not required ,jquery will automatically iterate all elements with class help-inline
in DOM. .each()
用于迭代'.help-inline'
的.each()
,jquery将使用DOM中的class help-inline
自动迭代所有元素。
OR 要么
As far i understand your question you are cloning a field clicking '.example_button'
then one thing you can do is that hide the element when you are creating it otherwise there must be a event on which you want to hide '.help-inline'
elements,use that event with .on() and hide elements with class 'help-inline'
inside DOM. 据我了解您的问题,您正在克隆一个单击
'.example_button'
的字段,那么您可以做的一件事是在创建元素时将其隐藏,否则必须存在一个事件,您想在其中隐藏'.help-inline'
元素,将该事件与.on()一起使用,并在DOM中隐藏具有'help-inline'
类'help-inline'
元素。
Break the common code out into a function, and call it in both instances. 将通用代码分解成一个函数,然后在两个实例中都调用它。
function hideAllTheInlineHelps() {
$('.help-inline').hide(); // or .css('display', 'none')
}
$(document).ready(function() {
hideAllTheInlineHelps();
});
$(document).on('click', '.example_button', function() {
hideAllTheInlineHelps();
});
Thanks to @Kartikeya for pointing out that you want the function to run without clicking the button . 感谢@Kartikeya指出您希望函数在不单击按钮的情况下运行。
Looking at the docs for "nested_form" , it seems you can react to the nested:fieldAdded
event: 查看“ nested_form”的文档 ,看来您可以对
nested:fieldAdded
事件做出反应:
$(document).on('nested:fieldAdded', function(evt) {
hideAllTheInlineHelps();
// or $('.help-inline').hide();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.