0

问题:$(".price").hide();作品应用于已经渲染的元素,但是,当我通过 javascript 加载新模板时,价格类将可见。

问题:有没有办法在插入 DOM 时将样式应用于类的所有未来实例。

例子:

$(".price").hide();
$('body').append('<div class="price">19.00</div>'); // this should be hidden.
4

5 回答 5

3

您应该可以使用livequery做到这一点。

$('.price').livequery(function() {
    $(this).hide();
});

优点是这将涵盖现有的以及您添加到 DOM 的任何新元素。

编辑:正如其他人指出的那样,livequery 是为 jQuery 1.3-1.4 编写的。所以我不确定它对你的情况有多适用。让我看看 1.7.2 是否有任何等价物。查看此答案以获取有关在 jQuery 1.7+ 中模仿 livequery 功能的更多信息。

于 2012-07-02T18:27:16.573 回答
1

我认为最好的解决方案是使用辅助类:

CSS

.helper{
    display: none;
}

jQuery

$(".price").addClass('helper'); //for dyanmic addition to certain classes
$('body').append('<div class="price helper">19.00</div>');  //for adding afterward
于 2012-07-02T18:27:09.237 回答
1

不要这样做,而是让您的切换开关修改容器元素以添加或删除类。

然后,有一个如下所示的 CSS 规则:

.hidePrice .price{
    display:none;
}​

切换按钮时,只需切换容器元素上的 hidePrice 类。

见:http: //jsfiddle.net/bXChZ/

于 2012-07-02T19:15:07.983 回答
0

这对我有用:

使用 jQuery:

$('<style id="priceVisibility">div.results .price {display: none; }</style>').appendTo('head');

没有 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);
于 2012-07-02T19:03:45.827 回答
0

您可以在 <body> 标记中添加一个类,然后使用 CSS 隐藏 .price 元素。例如

jQuery:

$('body').addClass('hide-price');

CSS:

.price {display: block}
.hide-price .price {display: none}
于 2012-07-02T19:15:47.373 回答