关于javascript:jquery在node-webkit上无法正常工作

jquery not working well on node-webkit

我正在练习node-webkit作为Node.js的初学者。
我的主页是一个简单的html页面,其中包含main.js脚本

我已经使用npm install jquery

安装了jquery

index.html

1
2
3
4
5
6
7
8
<!-- index.html -->
...
<script src="js/main.js">
</head>
<body>
Hi!
</body>
</html>

main.js

1
2
3
4
5
6
7
8
// main.js
const $ = require('jquery')

$(document).ready(function () {
  $('#demo').click(function () {
    $(this).text($(this).text() + 'Hi! ')
  })
})

如果我像<script src="path/to/jquery.js">一样在index.html中加载jquery,效果很好,但是如果我在main.js中需要jquery,则效果不佳!

我已经测试过:

  • main.js正确包含并使用本机js方法(例如document.getElementById('demo').onclick = ...)
  • 其他节点模块或库(例如vuelodash)或本机(例如fsurl)可以很好地工作。因此require函数的效果很好。
  • 虽然如上所述,我需要jquery,但是内联不能正常工作。

我也意识到$(document).ready(...)可以工作!但是真正的问题是$('#demo')是不确定的! (我检查了控制台-我使用的是node-webkit的SDK版本)

我不知道这是由于node-webkit还是其他我缺少的东西?


找到了解决方案,
我应该这样定义jquery:

1
window.$ = window.jQuery = require('jquery')

这仅仅是因为ECMAS中的变量范围

因此,如果我这样定义它,则可以在任何地方使用它