3

我想选择控件中的第一个选项,所以我写:

$("#MySelect").val($("#MySelect option:first").val());

现在继续将以下内容复制粘贴到谷歌闭包编译器中:

// ==ClosureCompiler==
// @output_file_name default.js
// @compilation_level ADVANCED_OPTIMIZATIONS
// @externs_url http://closure-compiler.googlecode.com/svn/trunk/contrib/externs/jquery-1.7.js
// ==/ClosureCompiler==

$("#MySelect").val($("#MySelect option:first").val());

你会得到这个错误:

在此处输入图像描述

我不明白为什么编译器会抱怨!有什么问题?

感谢您的建议。

4

2 回答 2

1
于 2012-08-10T21:19:10.927 回答
1

Many of the jQuery methods return different types based on the number and type of the input parameters. This behavior is akin to function overloading in a traditional language. However, JavaScript doesn't support traditional function overloading and jQuery mimics the behavior by inspecting the function arguments.

For .val, here's how the method would be annotated if function overloading was supported:

/** @return {number|string|Array.<string>} */
jQuery.prototype.val = function() {};

/**
 * @param {number|string|Array.<string>|function(number, *)} newVal
 * @return {!jQuery}
 */
jQuery.prototype.val = function(newVal) {};

Since there isn't function overloading, the actual signature for .val is a combination of both uses:

/**
 * @param {(number|string|Array.<string>|function(number, *))=} newVal
 * @return {!jQuery|number|string|Array.<string>|function(number, *)}
 */
jQuery.prototype.val = function(newVal) {};

Because of this, if you wish to use the return value of .val as the input for a separate call to .val, you must type cast the original return value to specify which usage you expect:

$("#MySelect").val(
    /** @type {number|string|Array.<string>} */
    ($("#MySelect option:first").val()) //note the extra parens
);

This behavior is described in a comment at the top of the jQuery externs file: http://code.google.com/p/closure-compiler/source/browse/trunk/contrib/externs/jquery-1.7.js#20

于 2012-08-13T13:22:30.177 回答