[英]Apply styles regardless if the element has been added to the DOM with jQuery
Problem: Applying $(".price").hide();
问题:应用
$(".price").hide();
works to elements already rendered, however, when I load a new template via javascript, the price class will be visible. 适用于已经渲染的元素,但是,当我通过javascript加载新模板时,价格类将可见。
Question: Is there a way to apply a style to all future instances of a class upon insertion into the DOM. 问题:有没有一种在插入DOM后将样式应用于类的所有将来实例的方法。
Example: 例:
$(".price").hide();
$('body').append('<div class="price">19.00</div>'); // this should be hidden.
You should be able to do this with livequery . 您应该可以使用livequery做到这一点。
$('.price').livequery(function() {
$(this).hide();
});
The advantage is that this will cover existing, as well as any new elements you add to the DOM. 优点是,这将覆盖现有的以及添加到DOM的任何新元素。
EDIT : As others have pointed out livequery was written for jQuery 1.3-1.4. 编辑 :正如其他人指出的那样,livequery是为jQuery 1.3-1.4编写的。 So I'm not sure how applicable it would be to your case.
因此,我不确定这将对您的情况适用。
Let me see if there is anything equivalent for 1.7.2. 让我看看是否有等同于1.7.2的东西。 Take a look at this answer for more information about mimicking livequery's functionality in jQuery 1.7+. 看看这个答案 ,以了解有关在jQuery 1.7+中模仿livequery功能的更多信息。
I think the best solution is to use a helper class: 我认为最好的解决方案是使用帮助器类:
CSS CSS
.helper{
display: none;
}
jQuery jQuery的
$(".price").addClass('helper'); //for dyanmic addition to certain classes
$('body').append('<div class="price helper">19.00</div>'); //for adding afterward
Instead of doing it this way, make your toggle switch modify a container element to add or remove a class. 而不是这样做,而是使切换开关修改容器元素以添加或删除类。
Then, have a CSS rule that looks like this: 然后,创建一个如下所示的CSS规则:
.hidePrice .price{
display:none;
}
When you toggle your button, just toggle the hidePrice class on your container element. 切换按钮时,只需切换容器元素上的hidePrice类。
See: http://jsfiddle.net/bXChZ/ 请参阅: http : //jsfiddle.net/bXChZ/
This worked for me: 这对我有用:
With jQuery: 使用jQuery:
$('<style id="priceVisibility">div.results .price {display: none; }</style>').appendTo('head');
Without jQuery: 没有jQuery:
// Appending style element to the head with a overriding style.
var style = document.createElement('style');
style.type = 'text/css';
style.id = 'priceVisibility';
style.innerHTML = 'div.results .price {display: none; }';
document.getElementsByTagName('head')[0].appendChild(style);
You could just add a class to the <body> tag, and then hide the .price elements with CSS. 您可以将一个类添加到<body>标记中,然后使用CSS隐藏.price元素。 Eg
例如
jQuery: jQuery的:
$('body').addClass('hide-price');
CSS: CSS:
.price {display: block}
.hide-price .price {display: none}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.