javascript - 单击整个元素以注册单选按钮值

标签 javascript jquery input radio-button label

我希望能够单击整个元素,而不仅仅是单选按钮和文本,以便注册与单选按钮关联的值。

<div class='btn'>
<input id = '4' class='btn4' type="radio" name='1' value='' >    
<label for = '4' class="label4">Question populated from jQuery goes here
</label></div>

当我用标签包装输入时,我丢失了 jQuery 放入元素内的文本。

我必须填充文本的函数是...

function populateQuestion(index) {
if (currentQuestion <=9){
$('.q_question').html(questionsArray[index]['question']);
for (var i = 0; i < 8; i++) {
    $('.jumbotron').html('');
    $('.btn' + (i + 1)).val(questionsArray[index]['choices'][i]).prop('checked', false);
  $('.label' + (i + 1)).html(questionsArray[index]['choices'][i]);
}
} else{ quizComplete(correctAnswers)}
}
populateQuestion(currentQuestion);

最佳答案

有趣的小问题。我尝试用一​​行 jQuery 来完成此操作,但很快意识到,由于正在更改的元素位于容器内部,因此尝试单击它们会重置它们(实际上使它们变得不可单击)。解决方案是在 CSS 中的容器顶部添加一个不可见的伪元素,这样您就无法实际单击单选按钮(或标签)。

$('div.btn').on('click', function() {
  $(this).children('input').prop('checked', !$(this).children('input').prop('checked'));
})
.btn {
  border: 1px solid red;
  padding: 12px;
  position: relative;
}
.btn::after {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='btn'>
  <input id='4' class='btn4' type="radio" name='1' value=''>
  <label for='4' class="label4">Question populated from jQuery goes here
  </label>
</div>

关于javascript - 单击整个元素以注册单选按钮值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34373505/

相关文章:

c - 为什么对 scanf 的调用会这样工作?这在标准中吗?

javascript - 每次遇到一个元素时将数组拆分为多个数组的最佳方法是什么?

javascript - jQuery 多个选择器,当某些元素可能存在或可能不存在时

javascript - Farbtastic jQuery 颜色选择器回调问题

jquery - 仅当先前的重新加载完成时才使用 jquery 重新加载页面

c++ - C++中的cin.fail()和!cin有什么区别?

javascript - 文件输入我做错了什么?

javascript - 如何在 backbone.js 中使用 subview

javascript - 在数据列表内切换 Div 标签

jquery - .text() 和 .html() 之间带有转义 < 和 > 字符的区别