jQuery: Find Closest Parent Element with Specific Class
$('#' + item_id).closest('.qcart_item').find('.qq_item_data').each(function() { var closestElement = $(this).closest('.qcart_item'); // do something with the closestElement });
This jQuery code snippet efficiently finds the closest ancestor element with the class 'qcart_item' for each element matching the '.qq_item_data' selector. Here's a breakdown:
- $('#' + item_id): This selects the element with the ID specified by the
item_idvariable. - .closest('.qcart_item'): This method traverses up the DOM tree from the selected element until it finds the nearest ancestor element with the class 'qcart_item'.
- .find('.qq_item_data'): This method searches within the closest 'qcart_item' element for all elements with the class 'qq_item_data'.
- .each(function() {}): This method iterates over each element found in step 3. Inside the function, the
closestElementvariable stores the closest ancestor 'qcart_item' element for the current iteration.
Practical Application:
Imagine you have a shopping cart where each item has a 'qcart_item' class, and each item has a quantity input field with the class 'qq_item_data'. You can use this code to update the quantity of an item in the cart when the quantity field is changed. For example:
$('.qq_item_data').on('change', function() {
var closestElement = $(this).closest('.qcart_item');
// Get the new quantity from the input field
var newQuantity = $(this).val();
// Update the quantity of the item in the cart using the closestElement
// ...
});
This code snippet uses the closest() method to easily find the parent item element and then uses the val() method to get the new quantity value from the input field. You can then use the closestElement variable to access other elements within the item, such as the price or the item name, to update the cart accordingly.
原文地址: https://www.cveoy.top/t/topic/qdbc 著作权归作者所有。请勿转载和采集!