【问题标题】:How to pass object/template as parameter in Javascript/jQuery如何在 Javascript/jQuery 中将对象/模板作为参数传递
【发布时间】:2011-03-09 02:03:00
【问题描述】:

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

【问题讨论】:

    标签: javascript jquery parameter-passing object-initialization


    【解决方案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)。然而,这纯粹是风格。

    【讨论】:

      【解决方案2】:

      你的语法有点不对劲,看起来像这样:

      $(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,这就是您在寻找有关此方面的更多信息时在谷歌上搜索的内容:)

      如果除了这些参数之外还需要其他个参数,您也可以将对象作为数组传入,而不是直接使用arguments

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-11
        • 2017-05-20
        • 1970-01-01
        • 2012-11-25
        • 2018-09-28
        • 2011-09-14
        • 1970-01-01
        • 2021-04-29
        相关资源
        最近更新 更多