应用样式,无论元素是否已使用 jQuery 添加到 DOM 中

Apply styles regardless if the element has been added to the DOM with jQuery

本文关键字:jQuery 添加 DOM 样式 是否 元素 应用      更新时间:2023-09-26

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

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

例:

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

你应该能够用livequery做到这一点。

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

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

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

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

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

.hidePrice .price{
    display:none;
}​

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

看:http://jsfiddle.net/bXChZ/

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

.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

这对我有用:

使用 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);
你可以添加一个

类到

标签,然后用CSS隐藏.price元素。

j查询:

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

.CSS:

.price {display: block}
.hide-price .price {display: none}