【问题标题】:Add click event to dynamically added button to kendo window content添加点击事件以动态添加按钮到剑道窗口内容
【发布时间】:2017-05-30 20:43:35
【问题描述】:

我有剑道窗口,并且我正在向剑道窗口动态添加内容。 内容有一个按钮,我想将点击事件附加到该按钮。 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);
                });

【问题讨论】:

  • 您在实际将其插入 DOM 之前使用 jQuery 选择尚未创建的按钮。我不知道kendo api,但是我会寻找一个在内容更改时调用的事件,然后将按钮代码作为回调执行。

标签: javascript jquery kendo-window


【解决方案1】:

你需要改变:

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

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

正如你提到的元素是动态创建的,所以它不是浏览器 dom 结构的一部分,因此不能用 jQuery 选择。使用上面的代码,jQuery 会监听 #window 元素内的 dom 结构的任何变化,因此您可以选择任何动态创建的元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-03
    • 1970-01-01
    • 2011-10-20
    相关资源
    最近更新 更多