简体   繁体   中英

Click event handler for dynamically-generated input/button?

Can I use exactly the same code to handle clicks for static and for Ajax-generated buttons? The reason I ask is that I can't get a click handler to work for an Ajax button, but if I write the equivalent static HTML, the click does work.

This code is the static version, which does work:

// in JS file:
$(function(){
   $('input.sButton').click(function(){
      var f = $.farbtastic('#picker');
      f.linkTo(this);
      return false;
   });
});

In the "static HTML":

<div id = "inputArea">
<label style="white-space: nowrap; line-height: 14px; height: 14px; vertical-align: bottom;">
<input id="sButton1" class="sButton" type="button" style="background-color: rgb(113, 16, 232);">
fubar1
</label>
</div>

The normal "dynamic HTML" looks like this:

<div id = "inputArea">
</div>

The Ajax code loads the buttons into 'inputArea'. I derived the static version of this code from Firebug. I ran the Ajax routine, then got the HTML view in Firebug, which included the server output, and cut-and-pasted it exactly into my static test code, which is reproduced above. In other words, I know that the static and dynamic HTML are equivalent.

But - the static code works, and the dynamic one doesn't. Firebug shows the JS click handler being entered for the static version, and the farbtastic colour picker pops up, but this doesn't happen in the dynamic code. Any ideas?

If you are using jquery 1.7+, use on instead of click

http://api.jquery.com/on/

$("body").on("click","input.sButton",function(){
 //do whatever you want
});

if you use a lower version of jquery, use live

$('input.sButton').live("click",function(){
 //do whatever you want
});
$('input.sButton').live('click', function(){
      var f = $.farbtastic('#picker');
      f.linkTo(this);
      return false;
   });

.live listens even for ajax content. Thsi should do the trick. Also, you may want to look into jquery .on() as well. Make sure you're using the latest jquery.

为此有一个jQuery live函数,请在此处查看

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM