2017-05-30 130 views
0

我有劍道窗口和im動態添加內容到劍道窗口。 內容有一個按鈕,我想將點擊事件附加到該按鈕。 jQuery是能夠找到從內容的按鈕,連接單擊事件然而單擊事件永遠不會被解僱添加點擊事件動態添加按鈕到劍道窗口內容

JSFiddle

的Html

<div id="example"> 
    <div id="window">  
    </div> 
</div> 

JQuery的

  $(document).ready(function() {     
        // in reality this contnet will be returned from ajax call 
        var dynamicContent ="<div><button id='btn' type='button'>Click Me</button></div>" 
        var myWindow = $("#window") 
        var button = $(dynamicContent).find("#btn"); 

        // show number of buttons found.      
        alert("found " + button.length + " button") 

        // attach click event to button 
             button.click(function(){ 
         alert("this is test");      
        }) 

        myWindow.kendoWindow({ 
         width: "600px", 
         height:"200px", 
         title: "My Window" 
        }).data("kendoWindow").center().open().content(dynamicContent); 
       }); 
+0

在您將其插入到DOM之前,您選擇了尚未創建的jQuery按鈕。 我不知道kendo api,但是我會尋找一個當內容發生變化時調用的事件,然後以回調的方式執行按鈕代碼。 – Strernd

回答

0

您需要更改:

button.click(function(){ 
    alert("this is test");      
}) 

$('#window').on('click', 'button', function(){ 
    alert("this is test");      
}) 

如你所提到的元件是動態創建的,所以它不是瀏覽器的一部分的DOM結構,並且因此不能與jQuery進行選擇。使用上面的代碼,jQuery會監聽#window元素中dom結構的任何更改,以便您可以選擇任何動態創建的元素。