【问题标题】:How do I call a JavaScript function with a variable name that is only known at runtime?如何使用仅在运行时知道的变量名调用 JavaScript 函数?
【发布时间】:2012-08-10 07:56:52
【问题描述】:

对于这个问题,我有一个 PHP 代码的 sn-p,它在一个目录中查找并返回一个文件列表。然后我遍历数组并使用 echo 将每个文件名存储为 JavaScript 变量

考虑以下示例,女巫不包括用于生成图像名称的 PHP:

//result of PHP
image1="cow.jpg"  
image2="pig.jpg"
image3="dog.jpg"

imgIndex=0 //global variable that will be incremented

function setBG(image) {
    someElement.style.backgroundImage= "url(/images/" + image + ")"
};

function nextBG(){
    imgIndex++
    currentIMG="image"+imgIndex;
    setBG(currentIMG);
};

当调用函数nextBG() 将不起作用。但这会:

function nextBG(){
    setBG(image1);
};

我认为它不起作用的原因是因为第二个示例是使用定义的变量 (cow.jpg) 的值调用函数。但是第一个例子是使用字符串"image1"调用函数,witch显然不是图像的路径名。

有没有办法让我使用变量image1,然后image2,然后image3等等来调用函数,而不会将它解释为只是一个字符串?

【问题讨论】:

    标签: javascript arrays string variables loops


    【解决方案1】:

    使您的变量成为对象的成员。然后您可以使用 [] 使用字符串访问对象成员:

    var images = {
      image1 : "cow.jpg",  
      image2 : "pig.jpg",
      image3 : "dog.jpg"
    };
    
    function nextBG(){
        imgIndex++
        currentIMG="image"+imgIndex;
        setBG(images[currentIMG]);
    };
    

    【讨论】:

      【解决方案2】:

      最简单的解决方案是将所有图像存储在一个数组中:

      var bgImages = [
          // All can be got with a call to encode your PHP array as JSON.
          "cow.jpg",
          "horse.jpg",
          "dog.jpg",
          "pig.jpg"
          ],
          imageIndex = 0,
          maxLength = bgImages.length - 1;
      
      function setBG(image) {
          someElement.style.backgroundImage= "url(/images/" + image + ")"
      };
      
      function nextBG(){
          var currentIMG = bgImages[imageIndex];
          setBG(currentIMG);
          imageIndex = imageIndex > maxLength ? 0 : imageIndex + 1;
      };
      

      【讨论】:

        【解决方案3】:

        那是因为 currentIMG 是一个字符串,而不是一个变量。这就是你想要做的。你有你的数组 $images,它只是图像名称。在您的 HTML 中,您可以这样做

        var images = <?php echo json_encode($images); ?>;
        

        然后你可以像这样使用 JavaScript

        for(var i=0; var i < images; i++)
        {
            setBG(images[i]);
        }
        

        【讨论】:

          猜你喜欢
          • 2020-11-02
          • 1970-01-01
          • 2018-03-31
          • 2019-02-23
          • 2013-05-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多