2

我在嘗試將我的第一個forray轉換爲jQuery。我試圖達到以下目的,儘管我不確定術語,所以會嘗試使用一種C#/僞代碼語法來解釋這個術語。如何在Javascript/jQuery中將對象/模板作爲參數傳遞

說我想要的(匿名)對象作爲參數,看起來像:

elemParameter { 
    elemId, 
    arg1, 
    optionalArg2 
} 

,我想對這些對象的數組/集合傳遞到我的功能

$(document).ready(function() { 
    $.myFunction(
     new { Id = "div1", Color = "blue", Animal = "dog" }, 
     new { Id = "div3", Color = "green" }, 
     new { Id = "div4", Color = "orange", Animal = "horse" } 
    ); 
} 

,然後在我的功能中,我需要訪問集合中的每個對象,例如:

(function($) { 
    $.myFunction(var elemParams) { 
     foreach (param in elemParams) { 
      $('#' + param.Id).onclick = function() { 
       this.css('background-color', param.Color); 
       alert(param.Animal ?? 'no animal specified'); 
      } 
     } 
    } 
} 

能有人給我幾個指針,以正確的語法來傳遞參數嗎?或者建議一個更好的方法來達到同樣的效果,如果這不是在javascript中使用正確的方式。

回答

3

你的語法,只是有點過了,它會是這個樣子:

$(function() { 
    function myFunction() { 
    $.each(arguments, function(i, arg) { 
     $('#' + arg.Id).click(function() { 
     $(this).css('background-color', arg.Color); 
     alert(arg.Animal || 'no animal specified'); 
     }); 
    }); 
    } 
    myFunction({ Id: "div1", Color: "blue", Animal: "dog" }, 
      { Id: "div3", Color: "green" }, 
      { Id: "div4", Color: "orange", Animal: "horse" });​ 
}); 

You can try a demo here,語法風格被稱爲JavaScript object literal notation,這是你使用Google的內容尋找解決此更多信息的時候: )

或者,如果您想要其他參數以外的其他參數,而不是直接使用arguments,則可以將對象作爲數組傳遞。

+0

哇,jsFiddle很酷!謝謝! – fearofawhackplanet 2010-06-28 11:18:12

1

您正在尋找「對象字面符號」。它看起來像這樣:

{ 
    propertyName: propertyValue, 
    propertyName2: propertyValue2 
} 

你不跟他們使用new關鍵字,他們只是像一個字符串字面結構(「富」)或數字(42)。同樣,你有數組常量:

["one", "two", "three"] 

這裏是你的榜樣更新:

$(document).ready(function() { 
    $.myFunction(
     // <== Start an array literal with [ 
     [ 
      // <== Colons rather than equal signs 
      { Id: "div1", Color: "blue", Animal: "dog" }, 
      { Id: "div3", Color: "green" }, 
      { Id: "div4", Color: "orange", Animal: "horse" } 
     // End the array literal with ] 
     ] 
    ); 
} 

注意,重要的是不要有尾隨逗號爲對象或數組文本,例如

["one", "two", "three", ] 
         ^--- Don't do that 
{foo: "bar", x: 27, } 
        ^------- Or that 

它們是否有效的問題是,目前還不清楚(它現在清楚近期第5版)和IE(至少)扼流圈他們。在JavaScript代碼


題外話,但通常屬性名是首字母大寫,用小寫字母開頭(所以,舉例來說,animal而非Animal)。然而,這是純粹的風格。

相關問題