如何捕获jquery中动态生成的按钮的点击事件

如何捕获jquery中动态生成的按钮的点击事件

本文介绍了如何捕获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功能/事件来工作。我也建议使用一个特殊的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.



<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中动态生成的按钮的点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 18:50