2

我正在尝试我的第一次尝试 jQuery。我正在尝试实现以下目标,尽管我不确定术语,因此将尝试使用一种 C#/伪代码语法的示例进行解释。

假设我想要一个(匿名)对象作为参数,看起来像:

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 中处理事情的正确方法,或者建议一种更好的方法来实现相同的目标。

4

2 回答 2

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" });​
});

您可以在此处尝试演示,语法样式称为JavaScript 对象文字表示法,这就是您在寻找有关此的更多信息时正在搜索的内容:)

或者,如果您需要除这些之外的其他参数,而不是直接使用,您可以将对象作为数组传递arguments

于 2010-06-28T10:59:42.477 回答
1

您正在寻找“对象文字表示法”。它看起来像这样:

{
    propertyName: propertyValue,
    propertyName2: propertyValue2
}

您不要对它们使用new关键字,它们只是像字符串(“foo”)或数字(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)。然而,这纯粹是风格。

于 2010-06-28T10:55:02.880 回答