jquery .val()和谷歌闭包编译器

时间:2012-08-10 21:06:07

标签: javascript jquery google-closure-compiler

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

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

现在继续将以下内容复制粘贴到google closure compiler

// ==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());

你会收到这个错误:

enter image description here

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

感谢您的建议。

2 个答案:

答案 0 :(得分:1)

你可以这样做$("#MySelect").prop("selectedIndex", 0)​​​​。它更简单并传递闭包编译器。

答案 1 :(得分:1)

许多jQuery方法根据输入参数的数量和类型返回不同的类型。此行为类似于传统语言中的函数重载。但是,JavaScript并不支持传统的函数重载,jQuery通过检查函数参数来模仿行为。

对于.val,如果支持函数重载,该方法将如何注释:

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

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

由于没有函数重载,.val的实际签名是两种用法的组合:

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

因此,如果您希望使用.val的返回值作为单独调用.val的输入,则必须键入强制转换原始返回值以指定您期望的用法:

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

此行为在jQuery externs文件顶部的注释中描述:http://code.google.com/p/closure-compiler/source/browse/trunk/contrib/externs/jquery-1.7.js#20

相关问题