常规JavaScript可以与jQuery混合使用吗?
问题描述:
例如,我可以使用此脚本(来自mozilla教程):
For example, can I take this script (from mozilla tutorial):
<html>
<head>
<script type="application/javascript">
function draw() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (30, 30, 55, 50);
}
}
</script>
</head>
<body onload="draw();">
<canvas id="canvas" width="150" height="150"></canvas>
</body>
</html>
并将此JavaScript与jQuery的document.ready混合而不是依赖于onload?
and mix this JavaScript with jQuery's document.ready instead of relying on onload?
答
是的,他们 JavaScript,你可以使用适合这种情况的任何功能。
Yes, they're both JavaScript, you can use whichever functions are appropriate for the situation.
在这种情况下,您可以将代码放在 document.ready
处理程序中,如下所示:
In this case you can just put the code in a document.ready
handler, like this:
$(function() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (30, 30, 55, 50);
}
});