Javascript 将单击事件添加到动态添加到剑道窗口内容的按钮

Javascript 将单击事件添加到动态添加到剑道窗口内容的按钮,javascript,jquery,kendo-window,Javascript,Jquery,Kendo Window,我有剑道窗口,我正在动态地向剑道窗口添加内容。 内容有一个按钮,我想将单击事件附加到该按钮。 jQuery能够从内容中找到按钮,附加click事件,但是click事件从未被触发 Html <div id="example"> <div id="window"> </div> </div> JQuery $(document).ready(function() {

我有剑道窗口,我正在动态地向剑道窗口添加内容。 内容有一个按钮,我想将单击事件附加到该按钮。 jQuery能够从内容中找到按钮,附加click事件,但是click事件从未被触发

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);
                });
$(文档).ready(函数(){
//实际上,这个contnet将从ajax调用返回
var dynamicContent=“单击我”
var myWindow=$(“#window”)
var按钮=$(dynamicContent.find(“#btn”);
//显示找到的按钮数。
警报(“找到“+按钮.长度+”按钮”)
//将单击事件附加到按钮
按钮。单击(函数(){
警报(“这是测试”);
})
myWindow.kendoWindow({
宽度:“600px”,
高度:“200px”,
标题:“我的窗口”
}).data(“kendoWindow”).center().open().content(dynamicContent);
});
您需要更改:

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


正如您所提到的,元素是动态创建的,因此它不是浏览器dom结构的一部分,因此不能使用jQuery进行选择。使用上述代码,jQuery将侦听
#window
元素中dom结构的任何更改,这样您就可以选择任何动态创建的元素。

在实际将其插入dom之前,使用jQuery选择尚未创建的按钮。我不知道剑道api,但我会查找在内容更改时调用的事件,然后作为回调执行按钮代码。
$('#window').on('click', 'button', function(){
  alert("this is test");                      
})