我们为什么要用({ })

它是代表吗?

使用这种语法意味着什么?

What are we wrapping with it?

例如:

$.ajaxSetup ({ // <-- THIS
    error: fError,
    compelete: fComp,
    success: fSucc
}); // <-- AND THIS

推荐答案

{} is object notation in JavaScript. For example:

$('selector').plugin({ option1: 'value' });

In this case you're passing an object containing your settings to the plugin. The plugin can deal with this as a object, whatever it's referenced as, for example:

settings.option1 //the option you passed in.

当然,它有更多的用途,但这是jQuery中最常见的示例..animate()$.ajax().css()等函数也是如此.任何接受属性的函数通常都使用此格式.


根据要求,还可以举几个例子:
传递的对象内的任何对象也可以是函数,而不仅仅是属性,例如:

$("<input>", {
  type: "text",
  focusin: function() { alert("Hi, you focused me!"); }
});    

这会将该输入的焦点事件设置为具有alert .另一种方法是扩展对象,向其添加属性,如下所示:

var person = { first_name: "John" };
$.extend(person, { last_name: "Smith" });
//equivalent to: 
person.last_name = "Smith";
//or:
person["last_name"] = "Smith";

Now person has the last_name property. This is often used by plugins as well, to take the default settings, then merge any settings you passed in, overwriting with any settings you specified, using defaults for the rest.

Why are we using it? Well...that's how JavaScript works, and in the jQuery spirit: it's an extremely terse and flexible way to pass information.

Jquery相关问答推荐

JQuery DateTimePicker-在 Select 中抓取星期几

$ 不是函数 - jQuery 错误

jquery如何判断ajax调用的响应类型

jQuery 与 javascript?

如何使用 jQuery 以编程方式触发对链接的点击?

数据表警告(表 id = 'example'):无法重新初始化数据表

用jquery查找div底部的位置

使用 jQuery 发送 JSON 数据

如何在 Jquery 中通过索引获取子元素?

延期与promise

在完成前一个请求之前中止新的 AJAX 请求

jQuery UI 中的 disableSelection 用于什么?

如何使用 jQuery 从 div 中删除 id 属性?

jQuery 如果 div 包含此文本,则替换该部分文本

在jquery中查找具有某个属性值的所有元素

jquery 检测某些类的 div 已添加到 DOM

jquery,id内类的 Select 器

D3 和​​ jQuery 有什么区别?

bootstrap 日期和时间 Select 器

使用 moment.js 将日期转换为字符串MM/dd/yyyy