有很多类似的问题,但我仍然无法弄清楚。
我有一组动态定义的单选按钮(按钮数量和标签都有变化)。
我只需要获取与选中的单选按钮关联的标签和编号。我怎么能这样做?
我做了一个JS fiddle表示当我点击任何按钮时,选中的收音机是“未定义”。这是代码:
$(document).ready(function() {
var myArray = ["never", "sometimes", "always"];
for (i = 0; i < myArray.length; i++) {
addradiobutton("radio", i + 1, label = myArray[i]);
}
function addradiobutton(type, number, text) {
var label = document.createElement("label");
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", type);
element.setAttribute("value", number);
element.setAttribute("name", type);
element.setAttribute("id", "radio_" + number);
label.appendChild(element);
label.innerHTML += text;
var foo = document.getElementById("questionAnswerRadio");
//Append the element in page (in span).
foo.appendChild(label);
}
$("#questionAnswerRadio").click(function(event) {
var currentSlideResult = 0;
currentSlideResult.answerChosen = $("#questionAnswerRadio :radio:checked + label").text();
currentSlideResult.numberChosen = $("#questionAnswerRadio :radio:checked + value").text();
alert(currentSlideResult.answerChosen)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="questionAnswerRadio"></div>
答案 0 :(得分:1)
$(this)
来获取所单击的单选按钮的值和标签currentSlideResult
$(this).parent().text()
change
事件而不是click
$(document).ready(function() {
var myArray = ["never", "sometimes", "always"];
for (i = 0; i < myArray.length; i++) {
addradiobutton("radio", i + 1, myArray[i]);
}
function addradiobutton(type, number, text) {
var input = $('<input />')
.attr({
type: type,
value: number,
name: type,
id: 'radio_' + number
});
$('<label />')
.text(text)
.prepend(input)
.appendTo('#questionAnswerRadio');
}
$("#questionAnswerRadio").on('change', ':radio', function(event) {
var currentSlideResult = {};
currentSlideResult.answerChosen = $(this).parent().text();
currentSlideResult.numberChosen = $(this).val();
alert(currentSlideResult.answerChosen);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="questionAnswerRadio"></div>