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の複製が表示されるので、合計6trになります。

セレクター用のjquerychange()ハンドラーを作成しましたが、どうすれば3つのtrを複製し、それらを下に追加できますか。

したがって、3を選択すると、次<tr>のように合計9が表示されます。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");
    }
});​

変更のたびに複製された行を削除する必要がない場合は、2行目を削除するだけです。

デモ: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 に答える