如何更改循环中生成的单选按钮的CSS样式

时间:2017-11-10 17:07:06

标签: javascript jquery html css

我想在选择单选按钮时更改单选按钮的颜色。

我知道默认方式是使用:checked,但这似乎不起作用。奇怪的是,:hover似乎有效,但在检查时我似乎无法设置单选按钮的样式。

一个复杂因素是我需要在JavaScript for循环中创建单选按钮,而不是在我的HTML文件中逐个创建。

我尝试过使用input[type=radio]或其变体,但无济于事。

抱歉,我对此有点新意并且正在尝试遵循教程:(

function buildQuiz(){

  // Store the HTML output
  const output = [];

  // Loop to iterate through each question...
  myQuestions.forEach(
    (currentQuestion, questionNumber) => {
      // Store the list of answer choices
      const answers = [];
      // Iterate through each answer in a question
      for(letter in currentQuestion.answerList){
        // Add HTML radio buttons for each answer choice
        answers.push(
          `<label class="radio">
            <input type="radio" name="question${questionNumber}" value="${letter}">
            ${currentQuestion.answerList[letter][0]}
          </label>`
        );
      }

      // Add this question and its answers to the output
      output.push(
        `<div class="slide">
          <div class="question"> ${currentQuestion.question} </div>
          <div class="answers"> ${answers.join('')} </div>
        </div>`
      );
    }
  );
  // Combine our output list into one string of HTML and put it on the page
  quizContainer.innerHTML = output.join('');
}

1 个答案:

答案 0 :(得分:1)

我不确定......你在找这样的东西吗?

&#13;
&#13;
for (var i = 1; i <= 10; i++) {
  $('form').append(`
    <input type="radio" name="choose" value="${i}">
  `)
}
&#13;
input {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  
  border-radius: 50%;
  width: 16px;
  height: 16px;

  border: 2px solid #999;
  transition: 0.2s all linear;
  outline: none;
  margin-right: 5px;

  position: relative;
  top: 4px;
}

input:checked {
  border: 6px solid red;
}
&#13;
<form></form>

<script src="https://unpkg.com/jquery"></script>
&#13;
&#13;
&#13;