我正在尝试第一次使用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方式。
答案 0 :(得分: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,这是您在查找有关此内容的更多信息时所使用的搜索内容:)
或者,如果除了这些参数之外还希望其他参数,则可以将对象作为数组传递,而不是直接使用arguments
。
答案 1 :(得分: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代码中的属性名称通常位于camelCase中,并以小写字母开头(例如,animal
而不是Animal
)。然而,这纯粹是风格。