请求修正并格式化指定的jQuery开关按钮函数代码
Looking at your original code, there are a couple of small issues that would prevent it from working correctly:
- The selector concatenation inside the function creates an invalid, redundant selector string
- The function parameter is being treated as both a jQuery object and a string, leading to confusion
Here's the corrected, properly formatted version that works as intended:
function switchButton(selector) { // Attach change event listener to the target input elements $(selector).on('change', function() { // Get the value of the checked switch input within the same parent container var result = $(this).closest('.switch-field').find('input[name="switch"]:checked').val(); alert(result); }); }
Key Improvements:
- Renamed
$paramtoselectorfor clearer readability (since it’s a CSS selector string, not a pre-wrapped jQuery object) - Used
$(this)inside the change handler to reference the element that triggered the event—this is more efficient and avoids selector duplication - Used
.closest('.switch-field')to target the parent container of the changed input, then.find()to grab the checked switch input. This ensures we’re only interacting with the relevant switch group, even if there are multiple switch fields on the page - Added quotes around the attribute value
name="switch"for proper, valid syntax
Proper Call Syntax:
switchButton('.switch-field input');
This works seamlessly with HTML structured like this (example):
<div class="switch-field"> <input type="radio" name="switch" value="option1" id="opt1"> <label for="opt1">Option 1</label> <input type="radio" name="switch" value="option2" id="opt2"> <label for="opt2">Option 2</label> </div>
内容的提问来源于stack exchange,提问作者Grufas
相关产品推荐
相关产品推荐

