jQuery clone()の例

jQuery clone()の例

jQueryclone()は、一致した要素のコピーを作成するために使用されます。 また、一致する要素とともにイベントハンドラーとデータをコピーする必要があるかどうかを示すブールパラメーターもサポートしています。

1. HTML要素を複製する

たとえば、次のhtmlコードを複製します。

 
I'm a small box
I'm a small small inner box

clone()を使用して上記の要素のコピーを作成し、「smallBox」のクラス名を含むdivタグの後にコピーした要素を配置します。

$('.smallBox').clone().insertAfter(".smallBox");

結果 :

 
I'm a small box
I'm a small small inner box
I'm a small box
I'm a small small inner box

2. イベントハンドラーの複製

次の例では、ボタンクリックイベントのクローンを作成します。「cloneButton1」というIDを含むボタンをコピーします。



デフォルトのclone() or clone(false) method, it will copy the button element only, but not the click() event handler.を使用している場合

$('#cloneButton1').clone().insertAfter("#cloneButton1");

一致した要素とともにclick()イベントハンドラをコピーするには、clone(true)を使用する必要があります。

$('#cloneButton1').clone(true).insertAfter("#cloneButton1");

自分で試してください









  

jQuery clone() example

I'm a small box
I'm a small small inner box