我有一個div。我們稱之爲#divResults
使用JQuery來檢查div內元素數量的變化
#divResults
將在其內部有N .divProducts
。當用戶點擊一個按鈕時,將執行一個asp.net方法。該方法將增加更多.divProducts
到#divResults
。我需要知道什麼時候.divProducts
的數量從例如40增加到80.
我需要使用JQuery以某種方式通知我何時發生此更改。
我怎麼能做到這一點?
我有一個div。我們稱之爲#divResults
使用JQuery來檢查div內元素數量的變化
#divResults
將在其內部有N .divProducts
。當用戶點擊一個按鈕時,將執行一個asp.net方法。該方法將增加更多.divProducts
到#divResults
。我需要知道什麼時候.divProducts
的數量從例如40增加到80.
我需要使用JQuery以某種方式通知我何時發生此更改。
我怎麼能做到這一點?
只是做
var divCount = $("#divResults .divProducts").length;
這應該讓您在#divResults
DIV與.divProducts
類元素的數量。現在由你來決定何時觸發它
編輯
,如果你的主要問題是什麼時候觸發它,那麼你可以把它放在按鈕的單擊事件處理程序。
var divCount = 0;
$("#buttonAddMore").on('click', function(){
divCount = $("#divResults .divProducts").length;
});
不能在div
使用change
事件。因此,有一件事是讓一個隱藏的元素具有相同的div數據。並更新其價值時的DIV更改,如內容:
$('#hiddenElem').val(myValue).trigger('change');
// This will trigger the change event
現在把一個事件監聽器此隱象:
$('#hiddenElem').change(function(){
// Do what ever you want to do here
});
請參考下面的代碼,希望能幫助you..you當你根據你的通知
$(document).ready(function() {
\t \t \t var numItems = $('.divProducts').length;
if(numItems > 40){
alert("hey its greater than 40");
}else{alert("its not yet 40");}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divResults">
<div class="divProducts">
</div>
<div class="divProducts">
</div>
</div>
沒有什麼特別的jQuery可以做到這一點。但是您可以使用MutationObserver來觀察元素childList
的更改。
var $target = $('#divResults');
$('#add').click(function(){
$target.append("<div class=\"divProducts\">Product</div>");
});
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log($target.children().length);
});
});
// configuration of the observer:
var config = { childList: true, };
// pass in the target node, as well as the observer options
observer.observe($target[0], config);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divResults">
</div>
<button id="add">Add a new div</button>
見[MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver)。 jQuery沒有構建方法來檢測對DOM做出的更改。如果更新通過AJAX發生,您可以檢查成功回調中的元素數量(無需使用MutationObserver)。 – empiric