为什么以下代码运行时单选按钮的文本无法呈现:
<div id='sctices'></div>
var result = [
{"id":"G84","value":"Mman, J"},
{"id":"G95","value":"Ekara, G"},
{"id":"G98","value":"Gedala, PS"}
];
var key, count = 0;
for(key in result)
{
var btnId = result[key].id;
var btnValue = result[key].value;
var radio = $("<input></input>",
{
type: 'radio',
name: 'gtice',
class: 'radio-default',
checked: false,
value: btnValue,
id: btnId,
text: btnValue
});
//radio.text(btnValue);// did not work
radio.insertAfter("#sctices");
radio.wrap("<div></div>");
}
请帮忙。奇怪的是,文本出现在生成的源中。感谢
答案 0 :(得分:3)
这是因为radio
输入不显示任何文本。通常的做法是在其旁边使用label
元素。尝试添加以下行:
var $label = $("<label></label>").text(btnValue).prepend(radio);
答案 1 :(得分:0)
这是我的版本
我认为来源看起来更干净DEMO
var result = [
{
"id": "G84",
"value": "Mman, J"},
{
"id": "G95",
"value": "Ekara, G"},
{
"id": "G98",
"value": "Gedala, PS"}
];
var key, count = 0;
for (key in result) {
var btnId = result[key].id;
var btnValue = result[key].value;
var $div = $('<div/>');
var $radio = $("<input/>", {
type: 'radio',
name: 'gtice',
class: 'radio-default',
checked: false,
value: btnValue,
id: btnId,
});
var $label = $("<label/>",{ 'for' : btnId}).text(btnValue);
$("#sctices").append($div.append($radio).append($label));
}
结果:
<div id="sctices">
<div>
<input type="radio" name="gtice" class="radio-default" value="Mman, J" id="G84">
<label for="G84">Mman, J</label>
</div>
<div>
<input type="radio" name="gtice" class="radio-default" value="Ekara, G" id="G95">
<label for="G95">Ekara, G</label>
</div>
<div>
<input type="radio" name="gtice" class="radio-default" value="Gedala, PS" id="G98">
<label for="G98">Gedala, PS</label>
</div>
</div>