2010-11-10 254 views
0

我有一个接收JSON响应的页面。如果JSON中有多个选项,它会根据更长的长度使用Javascript中的for循环动态生成一些单选按钮。jQuery动态生成单选按钮,然后传递值继续按钮

喜欢的东西

for (var i = 0; i < length; i ++){ 
    alert(i); 
     //draw the HTML radio buttons based on the data i++ 
    } 
     //value from radio button button gets passed to a continue button 

什么会做,在jQuery的最佳方法是什么?

回答

0

喜欢的东西

for (var i in json) { 
    var input = $('<input>', { 
    type: 'radio', name: 'group-name', 
    value: json[i], 
    'class': 'my_radio' 
    }); 
    $('body').append(input); 
} 

$('#continue').click(function() { 
    var selected = null; 
    $('input.my_radio').each(function() { 
     if ($(this).attr('selected')) 
      selected = $(this).val(); 
    }); 
    // do something with selected.... 
}); 

你有一个表单元素包围它,如果你需要的。顺便说一下,我没有测试过这个。