2014-02-27 161 views
0

我已經克隆像jQuery的克隆元素

<div class = "button1"> Button1</div> 
<div class = "text1Container"> 
    <div class="myButton"></div> 
</div> 
<div class = "text2Container"></div> 

這裏元素我的jQuery

$(".button1").click(function() { 
    $(".text1Container").clone().appendTo(".text2Container"); 
}); 

所以現在我想在「text2Container」 這樣一套點擊功能,但它沒有工作

//why not working 
$(".text2Container .myButton").click(function() { 
    alert('hello'); 
}); 

回答

3

您應該使用.on()爲動態創建的html元素綁定事件。試試這個:

$(".text2Container").on('click','.myButton',function() { 
    alert('hello'); 
}); 

而你在你的代碼中有錯字。與.button1更換button1

$(".button1").click(function() { 
    $(".text1Container").clone().appendTo(".text2Container"); 
}); 

DEMO

+0

不工作,同樣的問題 –

+0

我試圖與這.button1也沒有工作 –

+0

@UsmanAhmad:檢查演示鏈接。 – Unknown

0

你實際上並沒有分配點擊您button1。你缺少.類選擇:

$(".button1").click(function() { 
    $(".text1Container").clone().appendTo(".text2Container"); 

    $(".text2Container .myButton").click(function() { 
     alert('hello'); 
    }); 
}); 

注意,.myButton綁定代碼已與.button1 click處理程序是英寸您不能將事件綁定到尚不存在的元素。

Fiddle