如何为单选按钮点击函数绑定特定分组ID?
Hey there! I see you're trying to bind click events to radio buttons in specific groups, but your selector syntax was off. Let's get this sorted out step by step.
The Problem with Your Attempted Selector
Your tried selector $('input[type="radio",id="radioGroup1"]') doesn't work because it's trying to select either all radio inputs or the element with id="radioGroup1"—not the radio buttons inside the radioGroup1 container. To target child elements, you need to use a descendant selector.
Correct Implementation
1. Target Radio Buttons in a Specific Group
Use the parent container's ID followed by a space and the radio input selector to target only the radios inside that group:
// Bind click event to radio buttons in radioGroup1 $('#radioGroup1 input[type="radio"]').click(function() { var inputValue = $(this).val(); // Use .val() instead of attr("value") for reliability var targetBox = $("." + inputValue); $(".box").not(targetBox).hide(); targetBox.show(); }); // Bind click event to radio buttons in radioGroup2 (if you need separate logic) $('#radioGroup2 input[type="radio"]').click(function() { var inputValue = $(this).val(); // Add your custom logic for radioGroup2 here var targetBox = $("." + inputValue); // Example: If target boxes for this group have a different class $(".purpose-box").not(targetBox).hide(); targetBox.show(); });
2. Key Improvements
- Descendant Selector:
#radioGroup1 input[type="radio"]correctly targets all radio inputs inside theradioGroup1div. - Use
.val(): This method gets the current value of the input, which is more reliable thanattr("value")(especially if values are modified dynamically).
Quick Note on Your HTML
I noticed your radioGroup2 has two elements with the same id="chklain"—IDs must be unique in HTML! This can cause unexpected behavior in JavaScript/jQuery. Fix this by giving them unique IDs, like chklain1 and chklain2, or using classes instead if IDs aren't necessary.
内容的提问来源于stack exchange,提问作者Marviano

