0

HTML:

<table id="mytable">
<tr>
    <td>
        <select name="antal_tidspunkter" id="antal_tidspunkter">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
        </select>
    </td>
</tr>
<!-- These three <tr>s below should be duplicated to under each other -->
<tr>
    <td>This should be duplicated</td>
</tr>
<tr>
    <td>This too</td>
</tr>
<tr>
    <td>Hey, me too!</td>
</tr>
<!-- Above should be duplicated as of many you select in the select -->
</table>

JavaScript:

$(document).ready(function(){
    $('#antal_tidspunkter').change(function(){
        //
    });
});​

这是示例:http: //jsfiddle.net/PMXmY

我想这样做,当您将选择器更改为 2 时,它应该会出现当前 3 tr 的副本,因此总共 6 tr ..

我已经为选择器编写了 jquery change() 处理程序,但是我该怎么做才能复制三个 tr 并将它们附加在下面。

因此,当您选择 3 时,它应该出现总共 9 <tr>,如下所示:http: //jsfiddle.net/PMXmY/2/(这不起作用我刚刚在 html 中手动复制了 tr)

4

2 回答 2

1

这个解决方案怎么样?

$("#antal_tidspunkter").on("change", function() {
    $("#mytable tr:gt(3)").remove();
    for (var i = 1; i < this.value; i++) {
        $("#mytable tr:not(:first):lt(3)").clone().appendTo("#mytable");
    }
});​

如果您不需要每次更改时都删除克隆的行,只需删除第二行即可。

演示:http: //jsfiddle.net/PMXmY/16/

于 2012-06-07T22:16:11.123 回答
0
$(document).ready(function(){
    $('#antal_tidspunkter').change(function(){
        // get the number selected and subtract one to 
        // get the number of clones you need to append
        var num = parseInt($(this).val()) - 1;
        
        // the target to which the items will be appended
        var target = $('#mytable');

        //loop that will run as many times as the number that was selected
        for(i =0; i < num; i++) {
            //loop to clone and append only the first three tr's
            for(j = 1; j <=3; j++) {                
                // find the tr, clone it and append it to the target
                target.find('tr').eq(j).clone().appendTo(target);

            }
        }
    });
});​

演示

注释代码以便您理解它。

于 2012-06-07T21:26:23.123 回答