jQuery closest() vs. find() for Descendant Selection: A Common Mistake and Fix
The problem with the code is that the `closest()` method returns only the first ancestor element that matches the provided selector. So, using `.each()` after `closest()` doesn't make sense because it will iterate over that single matched element only.
If you want to target all elements with the class `.qcart_item` that are descendants of the element with the `item_id`, you can use the `find()` method instead of `closest()`.
Here's the corrected code:
$('#' + item_id).find('.qcart_item').each(function() {
// Your code here
});
This will find all elements with the class `.qcart_item` that are descendants of the element with the `item_id` and then iterate over each of them using the `each()` method.
原文地址: https://www.cveoy.top/t/topic/qc8n 著作权归作者所有。请勿转载和采集!