2
<select id="one">
    <option id="one_val_a" value="one">one</option>
    <option id="two_val_a" value="two">two</option>
    <option id="three_val_a" value="three">three</option>
</select>

<span id="pin"></span>

クローン#oneを作成し、そのIDを作成し#two、オプションIDを#one_val_b#two_val_bなどにする方法を教えてください。

$('#one').clone(true, true).attr('id', 'two').appendTo('#pin');

これにより、少なくともクローンのIDが変更されますが、オプションIDをどのように変更するのでしょうか。

Jsfiddle: http: //jsfiddle.net/C2zCZ/2/

4

5 に答える 5

2

別の方法として、正規表現を使用してoptionid属性を置き換えるため、元のオプションの数は関係ありませんselect

$('#one').clone(true, true)
    .attr('id', 'two').appendTo('#pin')
    .find("option").each(function() {
        $(this).attr("id", $(this).attr("id").replace(/\_a$/, "_b"));
    });

フィドルの例

于 2012-05-29T08:06:08.200 に答える
2
$('#one')
    .clone(true, true)   // perform the clone
    .attr('id', 'two')  // change the id
    .appendTo('#pin')    // append to #pin
    .children()          // get all options
    .attr("id", function(i, value) {  // processing on ids
        // replacing last charecter with its next charecter
        return value.replace(/[a-z]$/, function(char, index) {
            return String.fromCharCode(char.charCodeAt(0) + 1);
        });
    });

作業サンプル

于 2012-05-29T08:29:10.713 に答える
1
counter = 1;
$('#one').clone(true, true).attr('id', 'two').appendTo('#pin').find('option').each(function(){
    $(this).attr('id', 'option_id_' + counter++);
});

jsFiddleが更新され、機能しています:http: //jsfiddle.net/C2zCZ/4/

于 2012-05-29T07:59:01.520 に答える
1

別のワンライナー:

$('#one').clone(true, true).attr('id', 'two').each(function() {
    $(this).children().attr("id", function(i, value) {
        switch (i) {
            case 0: return "one_val_b";
            case 1: return "two_val_b";
            case 2: return "three_val_b";
        }
    });
}).appendTo('#pin');

デモ:http: //jsfiddle.net/C2zCZ/5/


もう1つの、より柔軟なワンライナー:

$('#one').clone(true, true).attr('id', 'two').appendTo('#pin')
    .children().attr("id", function(i, value) {

    var last = value.lastIndexOf("_") + 1;
    var char = value.substring(last).charCodeAt(0);
    return value.substring(0, last) + String.fromCharCode(char + 1);
});

デモ:http: //jsfiddle.net/C2zCZ/10/

于 2012-05-29T08:00:50.830 に答える
1

これがワンライナーです、

$('#one').clone(true).attr('id', 'two').children('option').attr('id',function(){
    return this.id.replace(/\a$/, 'b');
}).end().appendTo('#pin');

フィドル

PS

  1. の2番目の引数はclone()、最初の引数の値をコピーするため(デフォルト)、2番目の引数を渡す必要はありません。

  2. end()domに挿入した後はアクセスすべきではないと思うので使用しました。(私のアプローチはもっと速いはずですが、私はテストをしていません)

于 2012-05-29T08:28:58.480 に答える