未捕获的TypeError:undefined不是jQuery的函数

时间:2014-06-15 19:26:19

标签: javascript jquery coffeescript

我正在关注javascript / coffeescript / canvas教程,我有这个javascript代码:

(function() {
  $(function() {
    var canvas, context;
    console.log("DOM is ready");
    canvas = $('#myCanvas');
    context = canvas.getContext('2d');
    context.font = '40pt Calibri';
    context.fillStyle = 'blue';
    return context.fillText('Hello World!', 150, 100);
  });

}).call(this);

在致电canvas.getContext()时,我获得了Uncaught TypeError: undefined is not a function.

如果我将canvas = $('#myCanvas');替换为document.getElementById('myCanvas');,则可以正常使用。

您认为这是什么问题?谢谢!!

有关信息,这是我的HTML:

<!doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Demo</title>
    <script src="jquery-1.11.1.js"></script>
    <script src="test.js"></script>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
</body>
</html>

我原来的Coffeescript:

$ ->
    console.log("DOM is ready")
    canvas = document.getElementById('myCanvas');
    context = canvas.getContext('2d')
    context.font = '40pt Calibri';
    context.fillStyle = 'blue';
    context.fillText('Hello World!', 150, 100);

1 个答案:

答案 0 :(得分:10)

不同之处在于$('#myCanvas')返回jQuery对象而document.getElementById('myCanvas')返回canvas html元素。要获取画布上下文,您需要元素而不是对象。如果你想使用jQuery只需更改“canvas = $('#myCanvas');” to“canvas = $('#myCanvas')[0];”