动态创建js函数 [英] Dynamically create js function

查看:120
本文介绍了动态创建js函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要动态地(在循环中)绑定到多个的div的。点击()事件的函数。然后点击功能应隐藏点击股利。我试图它的方式,我失去了参考DIV,而这一点。不工作对我来说。

在这里的功能,我想绑定:

 函数do_hide(){
    is_anim = TRUE;
    $(本).animate({        不透明度:0.25,
        高度:切换,
        宽度:'切换'
    },5000,函数(){        is_anim = FALSE;
        this.hide();
    });
}

THX的任何帮助。

编辑:与ghayes的帮助下解

do_hide()在此被称为:

 为(VAR I = 0; I< N;我++)
{
P [I] = $(#BTN+第(i + 1));P [I]。点击(函数(){
   do_hide.call(本);
 });
}


解决方案

可以绑定作为do_hide当你调用它的范围。我建议像下面这样的模式:(工作的jsfiddle

  $('计算器')。点击(函数(){
   do_hide.call(本);
 }); VAR do_hide =功能()
 {
   is_anim = TRUE;
   $(本).animate({
     不透明度:0.25,
     高度:切换,
     宽度:'切换'
   },5000,
                  功能(){
                    is_anim = FALSE;
                    this.hide();
                  });
 };

希望这有助于!

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);
 });
}

解决方案

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!

这篇关于动态创建js函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆