开发者

how to capture the click event of a dynamically generated button in jquery

i see there is this syntax for detecting any butt开发者_StackOverflow中文版on 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?

EDIT: 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


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.

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>


Give the input an ID or class then use $(".class:button") or $("#id:button")


use the correct selector to identify the buttons you want ( http://docs.jquery.com/Selectors ) then add click functionality.

$(":button") selects ALL buttons. You want to limit that to the specific set you need

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜