【问题标题】:Check if variable is jQuery when importing with webpack使用 webpack 导入时检查变量是否为 jQuery
【发布时间】:2019-01-30 21:33:52
【问题描述】:

当您仅使用脚本标签从 CDN 加载 jQuery 时,测试您的变量是否为 jQuery 类型非常简单,但是当您使用 npm 和 webpack 导入时,我正在寻找一种简单的方法来执行此操作jQuery。我的示例导入是

import * as $ from 'jquery'

const $myElement = $('.my-element')

const isJQuery = ($element) => {
  return (
    typeof $element === 'object' &&
    $element.length &&
    $element[0] instanceof HTMLElement
  )
}

console.log(isJQuery($myElement)) // prints true

是否有更先进的方法来检查 $myElement 是否包含有效元素?

使用npm和webpack导入jQuery时,没有变量window.jQuery或window.$。

【问题讨论】:

    标签: jquery npm webpack


    【解决方案1】:
    import * as $ from 'jquery';
    
    const isJQuery = $element => $element instanceof $;
    
    const $myElement = $('.my-element');
    
    console.log(isJQuery($myElement)) // prints true
    
    

    $myElement isntanceof $ 在通过 Webpack 加载 jQuery 时也会返回 true

    【讨论】:

    • var $myElement = $('.my-element') undefined $myElement instanceof $ VM13544:1 Uncaught TypeError: Function has non-object prototype 'undefined' in instanceof check at Function.[Symbol. hasInstance] () at eval (eval at isJQuery (index.js:NaN), :1:12) at isJQuery (index.js:20) at SimpleGraph.checkOptions (index.js:39) at new SimpleGraph (index.js:35) at eval (index.js:11) at Module../line-graph/index.js (line-graph.js:97) at webpack_require (line -graph.js:20) 在 line-graph.js:84 在 line-graph.js:87
    • 您是否尝试过以这种方式导入?:import $ from 'jquery';
    • 是的,还是报错:“函数有非对象原型”
    猜你喜欢
    • 2010-12-23
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    相关资源
    最近更新 更多