我正在尝试动态创建单选按钮。然后在表格列中添加这些单选按钮。代码正在运行,但单选按钮出现没有标签。这是代码段
var $td = $('<td></td>');
for(i=0; i<factorOptions.length; i++){
var checked = false;
var factorOption = factorOptions[i];
if (factorOption.toUpperCase() === selectedFactor.toUpperCase()) {
checked = true
}
var $radioInput = $('<input />', {
type: 'radio',
id: ruleId +'-factor-' + i,
name: ruleId +'-factor',
'value': factorOption,
'checked': checked,
'text' : factorOption
});
$radioInput.before($("<label />")
.attr("for", $radioInput.attr("id"))
.text($radioInput.val()));
$td.append($radioInput);
}
我也试过$radioInput.after()
,但结果是一样的。我做错了什么?
当我在浏览器中看到该列时,它看起来像这样
<td>
<input name="1-factor" id="1-factor-0" type="radio" value="Once">
<input name="1-factor" id="1-factor-1" type="radio" checked="checked" value="Each">
</td>
由于
答案 0 :(得分:1)
看起来您可能很快就会致电.append
:
var $radioInput = $('<input />', {
type: 'radio',
id: ruleId +'-factor-' + i,
name: ruleId +'-factor',
'value': factorOption,
'checked': checked,
'text' : factorOption
});
$td.append($radioInput); // add it here
$radioInput.before($("<label />")
.attr("for", $radioInput.attr("id"))
.text($radioInput.val()));
// $td.append($radioInput); remove from here
在使用.before