Dynamically create js function

2019-08-05 18:18发布

问题:

I want to dynamically (in a loop) bind a function to the .click() event of several divs. The click function should then hide the clicked div. The way i was trying it, i lost the reference to the div, and "this." is not working for me too.

here the function i want to bind:

function do_hide() {  
    is_anim = true;  
    $(this).animate({

        opacity: 0.25,
        height: 'toggle',
        width: 'toggle'
    }, 5000, function() {

        is_anim = false;
        this.hide();
    });
}

thx for any help.

EDIT: solution with the help of ghayes

do_hide() is called here:

for (var i = 0; i < n; i++)
{    
p[i] = $("#btn"+(i+1));

p[i].click(function() {
   do_hide.call(this);
 });
}

回答1:

You can bind the scope for 'do_hide' when you call it. I would suggest a pattern like the following: (working JSFiddle)

 $('.stackoverflow').click(function() {
   do_hide.call(this); 
 });

 var do_hide = function()
 {  
   is_anim = true;  
   $(this).animate({
     opacity: 0.25,
     height: 'toggle',
     width: 'toggle'
   }, 5000, 
                  function() {
                    is_anim = false;
                    this.hide();
                  });
 };

Hope this helps!



回答2:

You can use jquery live for this purpose.

Simple write the code to hide in the function which you are binding in live e.g. $(this).hide()



回答3:

Jatin has the solution you are looking for.

Were you binding the click event only once, or every time you create a new div?

In any case, if you use the .live method to bind, it will bind events as the elements are created.

Adding this anywhere on your page should make it work:

$('div').live('click',do_hide);

http://jsfiddle.net/E65wk/



回答4:

$('divselector').click(do_hide);

This must do the trick. Or is there another code in your click binding ?