jQuery: Add and Remove Class on Click (Excluding Non-Closest Elements)
You can achieve this functionality using jQuery's 'closest()' and 'hasClass()' methods. Here's an example:
HTML:
<div class='addclass'>Element 1</div>
<div class='addclass'>Element 2</div>
<div class='addclass'>Element 3</div>
JavaScript:
$(document).ready(function() {
$('.addclass').click(function() {
// Check if the clicked element already has the class 'selected'
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
} else {
// Remove the class 'selected' from other elements except the closest one
$('.addclass').not($(this).closest('.addclass')).removeClass('selected');
$(this).addClass('selected');
}
});
});
In this code, we're attaching a click event handler to all elements with the class 'addclass'. When an element is clicked, it checks if it already has the class 'selected'. If it does, the class is removed. If it doesn't, the class 'selected' is added.
Additionally, we use the 'closest()' method to find the closest ancestor element with the class 'addclass' and exclude it from the elements where the 'selected' class is removed.
原文地址: https://www.cveoy.top/t/topic/qosz 著作权归作者所有。请勿转载和采集!