9

我正在尝试使用 jquery 即时将选择框转换为单选按钮,但我不确定最好的方法。

示例 HTML:

  <form id="product">    
    <select name="data[123]">
      <option value="1">First</option>
      <option value="2">Second</option>
      ......
      <option value="n">xxxxxx</option>
    </select>
  </form>

我想在页面加载时使用 jquery 将其转换为:

<form id="product">
  <input type="radio" name="data[123]" value="1" />
  <label for="data[123]">First</label><br/>
  <input type="radio" name="data[123]" value="2" />
  <label for="data[123]">Second</label><br/>
  ......
  <input type="radio" name="data[123]" value="n" />
  <label for="data[123]">xxxxxx</label><br/>
</form>

而且它需要是动态的,因此它将为每个选择框和里面的每个选项动态循环(因为不同的产品有不同的选项)

我试图找出最好的方法。要么首先获取所有值的多维数组,然后构建单选按钮..要么在循环中一次换出一个。目前正在尝试前者,但我想我可能想多了:

$(document).ready(function(){

    //Get Exising Select Options    
    $('form#product select').each(function(i, select){
        $(select[i]).find('option').each(function(j, option){
            //alert($(option).text());
            option[j] = [];
            option[j]['text'] = $(option).text();
            option[j]['val'] = $(option).val();
        });
    });


    //Remove Select box
    $('form#product select').remove();
});

有没有人尝试过这个或有一些我想念的秘密/更简单的方法?

4

2 回答 2

28

我把它放在一起,并在几个浏览器中进行了测试,似乎都处理得很好。它将从元素中取出数据并为每个<option>元素创建数据,然后删除选择框。<input/><label/><br/>

//Get Exising Select Options    
$('form#product select').each(function(i, select){
    var $select = $(select);
    $select.find('option').each(function(j, option){
        var $option = $(option);
        // Create a radio:
        var $radio = $('<input type="radio" />');
        // Set name and value:
        $radio.attr('name', $select.attr('name')).attr('value', $option.val());
        // Set checked if the option was selected
        if ($option.attr('selected')) $radio.attr('checked', 'checked');
        // Insert radio before select box:
        $select.before($radio);
        // Insert a label:
        $select.before(
          $("<label />").attr('for', $select.attr('name')).text($option.text())
        );
        // Insert a <br />:
        $select.before("<br/>");
    });
    $select.remove();
});
于 2010-01-08T17:24:58.320 回答
1

你在正确的轨道上。迭代并将选择数据收集到变量中,并尽可能少地调用 DOM 操作(为了提高效率)来创建无线电输入。

于 2010-01-08T17:21:31.557 回答