开发者

How to put a click function inside a callback function?

开发者 https://www.devze.com 2022-12-08 21:26 出处:网络
I\'m using this plugin: http://www.fyneworks.com/jquery/star-rating/ Is it possible to put a click function inside a callback function like this?

I'm using this plugin: http://www.fyneworks.com/jquery/star-rating/

Is it possible to put a click function inside a callback function like this?

$('.auto-submit-star').rating({ 
  callback: function(value, link){ 
    $('.myclass').click(function(){
      alert($(this).attr('id'));
    });
    alert($(this).attr('id'));
  } 
});

The callback function will stop working once I add the click function. I need to do this because if the user clicks any stars, I can pick up the id of the star, but if the user clicks the cancel button I can't pick up the id of the cancel somehow.

Assuming you can use a click funct开发者_如何学Cion inside the callback, would it still trigger it though? Because after you click it, it triggers the callback, would it still trigger my click function inside?

If I keep the click function separate things will still work, but then I'd have to repeat a bunch of code inside both functions.


To prevent multiple actions from taking place when clicking, you need to destroy the previous event before adding a new one (otherwise they'll just stack on top of each other). In order to destroy (i.e. kill) an event, you need to:

$('.auto-submit-star').rating({ 
  callback: function(value, link){ 
    $(".myclass").die("click").live("click", function(){
      alert($(this).attr('id'));
    });
  } 
});

Alternatively (and preferably), don't attach the click event from within the callback... do it separately.

$(".myclass").live("click", function(){
    alert($(this).attr('id'));
});
$('.auto-submit-star').rating()

Good luck with your project.


Try using the live handler

$(".myclass").live("click", function(){
  alert($(this).attr('id'));
});


Instead of binding the click on the callback, have you considered using the .live(type, fn) event of jQuery?

http://docs.jquery.com/Events/live#typefn

0

精彩评论

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