簡體   English   中英

如何使用僅在運行時知道的變量名稱調用JavaScript函數?

[英]How do I call a JavaScript function with a variable name that is only known at runtime?

對於這個問題,我有一段PHP代碼,它在目錄中查找並返回一個文件列表。 然后,我遍歷數組並使用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"調用函數,這顯然不是圖像的路徑名。

有沒有辦法讓我使用變量image1調用函數,然后使用image2然后使用image3等,而不會將其解釋為字符串?

最簡單的解決方案是將所有圖像存儲在一個數組中:

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

使變量成為對象的成員。 然后,您可以使用[]使用字符串訪問對象成員:

var images = {
  image1 : "cow.jpg",  
  image2 : "pig.jpg",
  image3 : "dog.jpg"
};

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

那是因為currentIMG是一個字符串,而不是一個變量。 這是你想要做的。 你有你的數組$ images,這只是圖像名稱。 在HTML中,您可以執行此操作

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

然后你可以使用JavaScript

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM