2010-12-29 10 views
1

私は、私のperlスクリプトを使用する代わりに、jqueryを使ってドロップダウンメニューの複製を作成することにしました。私は問題になった。jquery、クローニングの問題とユニークなIDの保持!

私は複数回クローンする一連のドロップボックスを持っています。構造は次のようである:。

<div id="org_dropmenus_asdf"> 
    <table border="0"> 
    <tr> 
    <td valign="top"> 
     <select name="wimpy_asdf_1" id="wimpy_asdf_1" size="4"> 
      <option value='1'>1</option> 
      <option value='2'>2</option> 
     </select>; 
    </td> 
    <td valign="top"> 
     <select name="monkey_asdf_1" id="monkey_asdf_1" size="4"> 
      <option value='c'>c</option> 
      <option value='d'>d</option> 
     </select>;  
    </td> 
      </tr> 
      </table><p> 
    </div>|; 

IクローンVAR $ cloneDiv = $( '#のorg_dropmenus_asdf')クローン();

asdf_1( "1")とインクリメントを新しい値で検索して置き換える方法はありますか?

答えて

1

あなたはこの線に沿って何かをする必要があります。

var counter = 1; 
$cloneDiv = $('#org_dropmenus_asdf').clone().find('[id]').attr('id', function(idx, oldId){ 
    return oldId.substr(0, -1) + counter; 
}).attr('name', function (idx, oldName) { 
    return oldName.substr(0, -1) + counter; 
}); 

あなたはcounterたびにインクリメント、繰り返しこれを行うことができます。最後の文字は削除されるため、このコードは9までしか動作しません。さらに多くの文字を削除する必要があります。

id属性はorg_dropmenus_asdf id属性を変更しないことに注意してください。これも有効なDOMで変更する必要があります。

+0

これは、選択タグを含むすべてのidsを検索しますか? – Gordon

1
function incrementId(idString) { 

    // split it at the underscore 
    var pieces = idString.split("_"); 

    // if there is a fourth element, then it just needs incrementing 
    if (pieces[3]) { 
     pieces[3] = parseInt(pieces[3]) + 1; 

    // if not, then it needs to be added 
    } else { 
     pieces[3] = "1"; 
    } 

    // reconstruct the ID by joining with the underscore character 
    return pieces.join("_"); 
} 

$cloneDiv = $('#org_dropmenus_asdf').clone(); 

// get the ID of the last 'org_dropmenus_asdf' div and increment 
var lastDivId = incrementId($("div[id^=org_dropmenus_asdf]:last").attr("id")); 

// get the IDs of the contained select elements, and increment 
var selectIds = $("div[id^=org_dropmenus_asdf]:last select").map(function() { 
    return incrementId(this.id); 
}).get(); 

alert(lastDivId); 
alert(selectIds); 

部分的なデモ+コンセプトの証明:http://jsfiddle.net/karim79/fL9ve/2/

+0