如何为子元素input值为空的父级li元素添加类?
Solution
To get this working, we can use jQuery's :has() selector to target the exact <li> element that contains an <input> with an empty value, then add the active class to it when the clear button is clicked. Here's how to adjust your code:
Modified JavaScript Code
$('#btn-modal-clear').on('click', function() { $('.select-name').multiselect('select', ['']); $('.select-name').multiselect('updateButtonText'); // Target the li with an empty-value input and add the active class $('li:has(input[value=""])').addClass("active"); });
Breakdown of the Selector
li:has(input[value=""]): This finds every<li>element that has a descendant<input>withvalue=""— exactly the element we need to target..addClass("active"): Applies theactiveclass to that matching<li>, which updates your HTML to match the expected result.
If you want to make sure no other <li> elements have the active class (to avoid multiple active items), add a line to remove the class first:
$('#btn-modal-clear').on('click', function() { $('.select-name').multiselect('select', ['']); $('.select-name').multiselect('updateButtonText'); // Remove active class from all lis first $('li').removeClass("active"); // Add active class to the target li $('li:has(input[value=""])').addClass("active"); });
Resulting HTML
<li>...</li> <li class="active"> <a class="myCheckboxLink" tabindex="0"> <span class="myCheckboxSpan"> <i class="fa fa-check fa-check-checkbox" aria-hidden="true"></i> </span> <label class="radio"> <input value="" type="radio">Name </label> </a> </li> <li>...</li>
内容的提问来源于stack exchange,提问作者Philipp M
相关产品推荐
相关产品推荐

