我有一组简单的实际工作的语句(我已经运行了该代码并且它做了我期望的)如下所示:
result_xml = result.jqxhr.responseXML;
a = jQuery("data[name='calendar']", result_xml).text();
new_calendar = jQuery.parseHTML(a);
jQuery("div.calendar").html(jQuery("div.calendar table.calendar-table", new_calendar));
result
来自 AJAX 回复,您应该识别 jqxhr
字段。
我希望 a
是一个字符串,因为我用 text()
得到了一个数据 block 。数据是我保存在 XML 文档中的 HTML 字符串。所以我可以这样转换它:
a = /** @type {string} */ jQuery("data[name='calendar']", result_xml).text();
现在我将该字符串转换为 HTML DOM,认为它是一个元素:
new_calendar = /** @type {Element} */ jQuery.parseHTML(a);
这就是我得到这个奇怪错误的地方:
WARNING - invalid cast - must be a subtype or supertype
from: (Array.<(Element|null)>|null)
to : (Element|null)
所以 parseHTML()
会返回一个元素数组(或 null)?
然后我尝试在 html()
函数中使用 parseHTML()
的输出,我也很难理解发生了什么上。
WARNING - invalid cast - must be a subtype or supertype found : (Array.<(Element|null)>|null)
required: (Document|Element|Object.|jQuery|null|undefined)
坦率地说,我不明白为什么 Google 编译器会使得一个函数的输出不能成为另一个函数的输入,即使它在现实世界中工作得很好。
Element
数组会被视为Document
吗?
最后(是的!所有这些都是 3 行 JavaScript!)关于 html()
函数的输入,我得到了另一个错误:
WARNING - actual parameter 1 of jQuery.prototype.html does not match formal parameter found : jQuery
required: (function (number, string): ?|string|undefined)
jQuery("div.calendar").html(jQuery("div.calendar table.calendar-table", new_calendar));
在这里,它也适用于现实世界……jQuery 对象会自动转换为字符串,然后重新转换为一组要添加到我的日历中的标签吗?
所有这些都是闭包编译器的正常限制吗?
根据乍得的回答,我以这种方式更改了我的代码:
result_xml = result.jqxhr.responseXML;
a = /** @type {string} */ (jQuery("data[name='calendar']", result_xml).text());
new_calendar = jQuery.parseHTML(a);
jQuery("div.calendar").empty().append(jQuery("div.calendar table.calendar-table", new_calendar[0]));
- 我在闭包中将
text()
输出转换为字符串; - 我使用
new_calendar
的元素 0 而不是直接使用new_calendar
。 - 我将
html()
更改为empty().append()
因为append()
函数接受一个jQuery
对象作为输入
这让闭包编译器很高兴。
最佳答案
是的,这绝对是预期的行为。有很多东西在 JavaScript 中“有效”。当被要求时,闭包编译器会尝试强制执行良好的行为。
至于 jQuery - 这些是已发布的 jQuery API 的正常限制。使用 jQuery,代码通常支持未记录的行为(就像您列出的那样)。然而,jQuery 团队可以随时更改未记录的行为。
如果您不匹配列为 API 规范的内容(并且 that definition 由社区维护 - 因此并不总是 100% 正确),Closure-compiler 会警告您。
相关规范如下:
- jQuery().html(string) - 设置为每个匹配元素内容的 HTML 字符串
- jQuery.parseHTML('string') - 返回:数组
关于javascript - 在使用 Google 闭包编译器时处理 jQuery parseHTML() 和 html(),,,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34734319/