You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用.find()多选择器无法为单选按钮添加checked属性求助

Fixing Radio Button Checked State with Combined Selectors

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:17:23