如何在Chrome应用中加入jQuery? [英] How to include jQuery in Chrome app?
问题描述
我需要在Chrome应用中访问一些jQuery方法,但我不确定如何包含API。我是前端开发的新手,我基本上正在寻找某种 .h #include
与我通常用更多类C语言做的平行。
I need access to some jQuery methods in my Chrome app, but am unsure how to include the API. I'm new to front-end development and am basically looking for some kind of .h #include
parallel to what I normally do with more C-like languages.
在我的manifest.json中,我尝试添加一个下载版本的jQuery的路径:
In my manifest.json, I tried adding a path to a downloaded version of jQuery:
{
"name": "my first app",
"manifest_version": 2,
"version": "0.0.1",
"minimum_chrome_version": "36.0.1941.0",
"app": {
"background": {
"scripts": [ "./assets/js/main.js", "./assets/third-party/js/jquery-2.1.1.js"]
}
}
}
在我的main.js文件中:
In my main.js file:
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create(
"index.html",
{
innerBounds: {width: 800, height: 510, minWidth: 800}
});
});
在我的index.js中,我没有任何width()方法的可见性:
In my index.js, I don't have visibility to any width() method:
(function() {
var ui = {
update: null,
};
var initializeWindow = function() {
console.log("Initializing window...");
for (var k in ui) {
var id = k.replace(/([A-Z])/, '-$1').toLowerCase();
var element = document.getElementById(id);
if (!element) {
throw "Missing UI element: " + k;
}
ui[k] = element;
}
ui.update.addEventListener('click', onUpdateClicked);
console.log("done initializing window");
};
var onUpdateClicked = function() {
console.log("update button was clicked");
updateProgressBar(0.25);
};
var updateProgressBar = function(percent) {
var elem = document.getElementById("progressbar");
console.log("Updating progress bar...");
var progress_width = percent * elem.width() / 100;
elem.find('div').animate({ width: progress_width }, 500).html(percent + "% ");
};
window.addEventListener('load', initializeWindow);
}());
推荐答案
清单中定义的脚本仅适用于后台事件页面(你可能根本不需要jQuery。
Scripts defined in the manifest only apply to background event page (where you probably don't need jQuery at all).
要在 index.html
中使用jQuery,你应该在< script>
标记中引用它的本地副本。小心按正确的顺序包含它。
To use jQuery in index.html
, you should reference a local copy of it in a <script>
tag. Be careful to include it in the right order.
这就是说,你的代码存在问题。
你混合了DOM元素和jQuery元素。
That said, there's a problem with your code.
You are mixing up DOM elements and jQuery "elements".
var elem = document.getElementById("progressbar");
返回一个DOM元素。您可以使用 $(elem)
将其转换为jQuery元素,或者以jQuery方式查询:
returns a DOM element. You can convert it to a jQuery element with $(elem)
, or query the jQuery way instead:
var elem = $("#progressbar");
一旦你这样做,你就可以访问jQuery方法了。
Once you do that, you'll have access to jQuery methods.
PS我将elements放在引号中,因为jQuery方法会操纵匹配元素集。在这种情况下,单个元素与id查询匹配。
P.S. I put "elements" in quotation marks because jQuery methods manipulate "sets of matched elements" instead. In this case, a single element matches an id query.
这篇关于如何在Chrome应用中加入jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!