簡體   English   中英

應用樣式,無論是否已使用jQuery將元素添加到DOM中

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

問題:應用$(".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

.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

而不是這樣做,而是使切換開關修改容器元素以添加或刪除類。

然后,創建一個如下所示的CSS規則:

.hidePrice .price{
    display:none;
}​

切換按鈕時,只需切換容器元素上的hidePrice類。

請參閱: http//jsfiddle.net/bXChZ/

這對我有用:

使用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);

您可以將一個類添加到<body>標記中,然后使用CSS隱藏.price元素。 例如

jQuery的:

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

CSS:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM