常规JavaScript可以和jQuery混合吗?

例如,我可以采取这个脚本( 从Mozilla教程 ):

<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?

是的,他们都是 JavaScript,你可以使用适合这种情况的function。

在这种情况下,您可以将代码放在document.ready处理程序中,如下所示:

 $(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); } }); 

为什么MichalBE得到低投入? 他是对的 – 使用jQuery(或任何库)只是为了在页面加载时启动一个函数是过度的,可能会让人们花费在移动连接上的钱,并放慢用户体验。 如果原始的海报不想在body标签中使用onload(而且他完全正确),那么在draw()函数之后加上:

 if (draw) window.onload = draw; 

或者,如果你想让一个以上的函数被执行的话, 由西蒙·威利森(Simon Willison)

 function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { if (oldonload) { oldonload(); } func(); } } } 

或者根本没有JavaScript加载function…

 <html> <head></head> <body> <canvas id="canvas" width="150" height="150"></canvas> </body> <script type="text/javascript"> var draw = 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); } } draw(); //or self executing... (function(){ var canvas = document.getElementById("canvas"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); ctx.fillStyle = "rgb(200,0,0)"; ctx.fillRect (50, 50, 55, 50); ctx.fillStyle = "rgba(0, 0, 200, 0.5)"; ctx.fillRect (70, 70, 55, 50); } })(); </script> </html> 

当然可以,但是为什么呢? 你必须包含一个链接到jQuery网页的<script></script>标记对,即: <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> 。 然后,您将加载整个jQuery对象只使用一个单一的函数 ,因为jQuery是一个JavaScript库,这将需要时间来上传计算机,它将执行比JavaScript更慢。

你可以,但要注意jQuery函数的返回types。 jQuery不会总是使用完全相同的JavaScript对象types,尽pipe通常它们会返回您希望从类似的JavaScript函数返回的子类。

你可以使用

 jQuery(document).ready(function(){} 

请注意,在代码之后,其余的代码将不得不是我想的 jQuery