如何捕获jquery中动态生成的按钮的点击事件 [英] how to capture the click event of a dynamically generated button in jquery

查看:486
本文介绍了如何捕获jquery中动态生成的按钮的点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到有这种语法检测任何按钮点击

i see there is this syntax for detecting any button click

<script type="text/javascript">
        $(document).ready(function() {
        $(":button").click(function(event) {
                alert("Thanks for visiting!" + this.value);
            });
        });
    </script>

但如果我只想检测页面上的特定按钮怎么办?

but what if i want to only detect a particular button on the page?

编辑:这似乎很好的按钮设置在开始,但在我的情况下,我使用jquery动态创建它们。看来这些按钮不打这个代码。任何想法

this seems fine for buttons that are setup at the beginning but in my case i am creating them dynamically with jquery. it seems those buttons dont hit this code. any ideas

推荐答案

您需要将click绑定到jQuery live 功能/事件来工作。我也建议使用一个特殊的CSS类或id在动态生成的按钮。这里是对甚至从jQuery.com的直播的描述。

You will need to bind "click" to the jQuery "live" function/event for that to work. I would also recommend using either a special CSS class or id on the dynamically generated button. Here is the description of the live even from jQuery.com.


当您绑定一个live事件时,
会绑定到页面上所有当前和未来的
元素(使用事件
委派)。例如,如果你绑定
a活动点击
上的所有li元素,然后在以后添加另一个li到
- 点击事件将
继续工作新元素
(这与bind不同,
必须在所有新元素上重新绑定)。

When you bind a "live" event it will bind to all current and future elements on the page (using event delegation). For example if you bound a live click to all "li" elements on the page then added another li at a later time - that click event would continue to work for the new element (this is not the case with bind which must be re-bound on all new elements).



<script type="text/javascript">
   $(document).ready(function() {
      //$(":button") would select all buttons
      //.className would work on an button with a CSS Class assignment of ClassName
      //Below shows how to do it on a specific ID
      $("#MyNewButtonID").live("click", function(event) {
         alert("Thanks for visiting!" + this.value);
      });
   });
</script>

这篇关于如何捕获jquery中动态生成的按钮的点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆