使用.find()多选择器无法为单选按钮添加checked属性求助
Hey there! I see the issue with your code right away—your selector logic is trying to nest two find() calls on input elements, which won't work because radio buttons don't contain other input elements. Let's break this down and fix it.
The Problem in Your Current Code
Your current selector chain:
var selector = $('.mark-container').find('input[name=' + val.key + ']').find('input[value=' + val.value + ']');
This first finds all inputs with the matching name attribute, then tries to find another input inside those elements. Since radio buttons are self-contained input elements, the second find() returns an empty jQuery collection—so calling prop("checked", true) does nothing.
The Solution: Combine Selectors in One find()
You need to target the single input element that has both the correct name and value attributes in a single selector. Also, wrap your attribute values in quotes to avoid issues with special characters:
var answers = [ { key: 'answerQ1', value: 3 }, { key: 'answerQ2', value: 5 }, { key: 'answerQ3', value: 2 }, { key: 'answerQ4', value: 1 }, { key: 'answerQ5', value: 4 }, ]; $.map( answers, function( val ) { // Combine name and value attributes in one selector var selector = $('.mark-container').find('input[name="' + val.key + '"][value="' + val.value + '"]'); selector.prop("checked", true); console.log(selector); // Now this should log the matched radio button });
Why This Works
Combining the name and value attribute selectors into one input[name="X"][value="Y"] tells jQuery to find the single input element that matches both conditions in the .mark-container context. This way, you're targeting exactly the radio button you want to check.
Bonus Tip: Use Template Literals for Cleaner Code
If you're using ES6+, template literals make the selector string much easier to read:
var selector = $(`.mark-container input[name="${val.key}"][value="${val.value}"]`);
内容的提问来源于stack exchange,提问作者Andrei Gabriel

