简体   繁体   English

javascript是否可以动态构建要调用的函数名称?

[英]javascript can I dynamically build a function name to call?

I have functions called 我有称为的功能

BeforeSlide1() {
...
}


BeforeSlide2() {
...
}

And I would like to be able to build the call to these dynamically in a loop, something like this: 我希望能够在循环中动态构建对这些对象的调用,如下所示:

        code = "BeforeSlide" + slide + "()"
        eval(code); 

Now this code of mine obviously doesn't work (if only it was that simple!) anyone know? 现在,我的这段代码显然不起作用(如果只是那么简单!),有人知道吗?

All right, I'll draw up the big picture. 好吧,我来画大图。

I have a slideshow run by a simple script 我有一个通过简单脚本运行的幻灯片

    function slideshow(slide) {
            if (pauseTimes[slide]>0) {
                    /* if there is another slide after the one currently showing... */

                //Call BeforeSlide-function if there is one
                code = "BeforeSlide" + slide + "();"
                try {
                    eval(code);                 

                } catch(e) {
                    /* do nothing since many slides don't have one */
                }           
                $('#slide'+slide).
                fadeIn(1500,function(){}).
                delay(pauseTimes[slide]).
                fadeOut(1500,function(){slideshow(slide+1);});
                ;
            }
            else {
                    /* if there is no more slide and we've reached the end, try to ajax-refresh the slideshow contents */
                ajaxUpdate();
            }
            }

Among the HTML of the slides themselves, the before- and afterfunctions are defined like this: 在幻灯片本身的HTML中,before和after函数的定义如下:

    /* fire the slideshow from slide 1 once document is finished loading */
    $(document).ready(function(){
        slideshow(1);
    });

    </script>

    </HEAD>

    <body id="slideshow_body">

    <script id='pauseTimesScript' type='text/javascript'>
    /* Define pauseTimes (array holding duration of each slide) */
    try {
            pauseTimes=null;
            pauseTimes=undefined;
            pauseTimes = new Array();   
            setPauseTimes();        
            /*alert('satte först till null, deklarerade sedan om.');*/
    } catch(e) {
            pauseTimes = new Array();   
            setPauseTimes();        
            /*alert('deklarerade utan att först sätta null.');*/
    }

    function setPauseTimes() {  

        pauseTimes[1]=2000;         

        pauseTimes[2]=2000;         

        pauseTimes[3]=2000;         

    }
    </script>

    <div id="avbrott">Tillfälligt avbrott, visar cachelagrat innehåll sedan 2012-10-31 16:37:35</div>

    <div id="canvas" style="width:1072px;height:732px;">

                <script language='text/javascript'>
                function BeforeSlide1(order=1) {
                alert('here goes slide '+order);

                }
                </script>
                        <div id="slide1" class="slide" style="z-index:1;">



    <div id="slide_bg" style="float:left;height:100%;width:100%;background-color:#ffffff;background-image:url('http://bglabs.evade.netdna-cdn.com/45875kli90/505.jpg');">

        <div style="background-color:#eeeeee;color:#000000;float:right;text-align:center;margin-top:30px;padding:10px;font-weight:bold;font-size:30pt;" id="preview_title">Egypt rocks!</div>
        <div style="clear:both;float:none;"></div>

        <p style="color:#000000;margin:10px 10px 0 20px;font-style:italic;font-size:38pt;" id="preview_data_6">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse feugiat pharetra eros, vitae ullamcorper tellus condimentum sit amet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Suspendisse in leo erat. Aliquam interdum molestie tortor, nec lacinia mauris viverra eget. Suspendisse aliquam tempor scelerisque. Proin vel purus nunc. Pellentesque ut sapien libero.<br />
    </p>

    </div>

The purpose of this BeforeSlide function is of course to do other stuff than produce an alert... 当然,此BeforeSlide函数的目的是做其他事情,而不是发出警报...

Please let me know how I should structure it in a better way! 请让我知道如何更好地构造它! =) =)

Don't use eval! 不要使用eval! Every function declared will be available through the window . 声明的每个函数都可以通过window Try this: 尝试这个:

function test() {
    alert("test");
}

var x = window['test'];
x();

Example fiddle 小提琴的例子

However, it would be much more logical to have a single function and to pass the integer as a parameter to that. 但是,拥有一个函数并将整数作为参数传递给它会更加合乎逻辑。

I would probably create an object like below, 我可能会创建一个如下所示的对象,

var myFunc = {
    BeforeSlide1: function () {
        //some stuff
    },
    BeforeSlide2: function () {
        //some stuff
    } 
}

And then you can simply call myFunc['BeforeSlide' + num] 然后您可以简单地调用myFunc['BeforeSlide' + num]

var code = "this.f = BeforeSlide" + slide + "() {...}";
eval(code);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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