我在嘗試將我的第一個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中使用正確的方式。
哇,jsFiddle很酷!謝謝! – fearofawhackplanet 2010-06-28 11:18:12