Javascript shorthand 三元运算符在设置为对象文字中的变量时不起作用

Javascript shorthand ternary operator not working when setting to variable in object literal

我试图在 JS 第一次 运行 时缓存变量,我需要检查 html 元素 .supports-no-touch 或 [=17] 上的 classes =](以确保根据使用的 Modernizr 版本捕获任一版本)。

当我运行这样的时候,

window.MyScript = window.MyScript || {};
MyScript.cacheSelectors = function () {
  MyScript.cache = {
    $slideoutNavDesktop: ($('.supports-no-touch #slideoutNav') || $('.no-touch #slideoutNav'))
    // OR
    // $slideoutNavDesktop: $('.supports-no-touch #slideoutNav') ? $('.supports-no-touch #slideoutNav') : $('.no-touch #slideoutNav')
  }
};
MyScript.cacheSelectors();
console.log( MyScript.cache.$slideoutNavDesktop );

console.log的结果是undefined空jQuery对象,如:

► [prevObject: n.fn.init(1), context: document, selector: ".supports-no-touch #slideoutNav"]

当我 运行 在控制台中使用相同的代码时,例如

console.log( $('.supports-no-touch #slideoutNav') || $('.no-touch #slideoutNav') );
console.log( $('.supports-no-touch #slideoutNav') ? $('.supports-no-touch #slideoutNav') : $('.no-touch #slideoutNav') );

我找到了正确的元素。

此外,我知道在页面加载时,html 元素 确实 具有 .no-touch class.

我做错了什么?

编辑:由于变量引用中的拼写错误,我收到 undefined

jQuery 总是 returns 非 null 对象引用,它总是真实的,所以这些都不起作用。我认为您在控制台中看到的结果是某种混乱的结果(控制台可能有点混乱)。

可以使用条件运算符,但需要勾选.length:

var x = $('.supports-no-touch #slideoutNav').length ? $('.supports-no-touch #slideoutNav') : $('.no-touch #slideoutNav');

...但是 DOM 查询两次。所以改为:

var x = $('.supports-no-touch #slideoutNav');
if (!x.length) {
    x = $('.no-touch #slideoutNav');
}

但是,更简单的答案是使用选择器组并取第一个(可能唯一)结果:

var x = $('.supports-no-touch #slideoutNav, .no-touch #slideoutNav').first();

注意:您的查询表明您在多个元素上具有相同的 ID。那是无效的。 ID 值 必须 是唯一的。因此,如果您要使用上述内容,我建议将 #slideoutNav 更改为 .slideout-nav 或类似内容,并将所涉及元素的 id="slideoutNav" 更改为 class="slideout-nav"(添加 slideout-nav 到他们现有的 class 属性(如果他们有的话)。