簡體   English   中英

jQuery prop()和Google Closure Compiler

[英]jQuery prop() and 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.8.js
// ==/ClosureCompiler==

function test() {

  var TheBool = $('#SomeElement').prop('checked');

  if (TheBool === true) {
     alert('checked');
   }
}

我收到一個警告,說這是一個總是評估為假的條件,即使我知道情況並非如此。

在此輸入圖像描述

您可以在http://closure-compiler.appspot.com/home上試試這個,並按照我的方式復制粘貼代碼(確保選中“優化:高級”)

如何使此警告消失?

這似乎是Google提供的externs文件中的一個錯誤。

他們錯誤地宣布jQuery.prototype.prop為返回一個字符串 jQuery的,而忽略了事實上它可以返回一個布爾值;

/**
 * @param {(string|Object.<string,*>)} arg1
 * @param {(string|number|boolean|function(number,String))=} arg2
 * @return {(string|!jQuery)}
 */
jQuery.prototype.prop = function(arg1, arg2) {};

......什么時候應該;

/**
 * @param {(string|Object.<string,*>)} arg1
 * @param {(string|number|boolean|function(number,String))=} arg2
 * @return {(string|boolean|!jQuery)}
 */
jQuery.prototype.prop = function(arg1, arg2) {};

我修復了這個並上傳了它 ,當使用那個externs聲明時,你的問題得到解決;

// ==ClosureCompiler==
// @output_file_name default.js
// @compilation_level ADVANCED_OPTIMIZATIONS
// @externs_url http://files.mattlunn.me.uk/permanent/jquery-1.8.js
// ==/ClosureCompiler==

function test() {

  var TheBool = $('#SomeElement').prop('checked');

  if (TheBool === true) {
     alert('checked');
   }

}

你可以通過不直接檢查=== true繞過這個; 只是if (TheBool)就足夠了。


FWIW,已在問題頁面上報告 ,並提交了補丁。

prop返回一個布爾值。 所以沒有必要檢查它是否=== true 只需使用:

if (TheBool) {
    alert('checked');
}

為了使閱讀時更容易理解,請嘗試:

var elementIsChecked = $('#SomeElement').prop('checked');
// `elementIsChecked` is either true or false

if (elementIsChecked) { // `elementIsChecked` is coerced into a boolean, but it already is, so it doesn't matter
    alert('checked');
}

也許你會明白為什么一開始就沒有必要。

if ()中使用的表達式被評估為true或false,無論結果是true還是false。 它恰好是prop確實返回真或假。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM