当您在each循环中修改jQuery集合时,修改后的集合是包含在其中还是仅包含原始集合?
例如
var collection = $("div");
$(collection).each(function(){
var originalDiv = $(this);
var cloneDiv = $(this).clone();
cloneDiv.insertAfter(originalDiv);
});克隆div现在是否包含在循环中,或者它只是原始的集合?
发布于 2020-05-26 19:24:21
collection中的jQuery对象不受循环中执行的clone和insertAfter调用的影响。jQuery对象是快照(像您从querySelectorAll获得的对象),而不是实时集合(像您从getElementsByTagName或getElementsByClassName或类似的对象获得的对象),clone和insertAfter都不会将其添加到collection中。
你可以很容易地证明这一点:
// Your code (without the unnecessary `$()` around `collection`
var collection = $("div");
collection.each(function(){
var originalDiv = $(this);
var cloneDiv = $(this).clone();
cloneDiv.insertAfter(originalDiv);
});
// Now, do another operation on the contents of `collection` -- notice how only
// the original contents are affected, not the divs created during the loop
collection.css("color", "blue");<div>a</div>
<div>b</div>
<div>c</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
即使您使用其中一个方法将元素添加到jQuery对象,jQuery方法通常也会创建新的jQuery对象,而不是修改您对其调用的jQuery对象的状态。(我认为这条规则是有例外的,但我不会立即想到这一点。)例如,您可以通过调用add来“添加”一个元素,但它不会更改调用它的jQuery对象;相反,它会创建并返回一个包含原始元素和新元素的新jQuery对象。
https://stackoverflow.com/questions/62021038
复制相似问题