Are JavaScript events working if i am using jQuery?
I am new at creating applications using jQuery but I am quite familiar with Javascript. Well, what I am trying to do is use the Javascript getElementById in order to draw an image in html5 canvas. My code is:
Include the jQuery and JQuery mobile:
<link rel="stylesheet" type="text/css" href="lib/jquery.mobile-1.0b1.min.css" />
<script type="text/javascript" src="lib/jquery-1.6.1.js"></script>
<script type="text/javascript" src="lib/jquery.mobile-1.0b1.min.js"></script>
The code with problem:
<div data-role="content">
<!--//TO DO canvas drawing-->
<canvas id="draw_area" width="295px" height = "390px"></canvas>
...
<script type="text/javascript">
var canvas = getElementById("draw_area");
var context = canvas.getContext('2d');
var map = new Image();
map.src = "./imgs/home_screen1.png";
map.onload = function (){
context.drawImage (map, 0, 0);
};
</script>
I also noticed that I am not able to use the
<body onload = "aFunction();">
not any开发者_运维百科 other Javascript event like "onclick".
Am I doing something wrong?
That should be:
var canvas = document.getElementById("draw_area");
Your script is running the getElementById
line as soon as it is loaded, which is failing (due to the missing document.
) and preventing the scripts on the rest of your page from executing.
Here's a quick demo to show you how script errors will prevent subsequent lines from executing.
Once that's fixed, as @swalk says, you should encapsulate that script so it runs on document.ready
to keep things tidy.
I suspect it's because you aren't using jQuery's dom ready function. Any JavaScript that manipulates/accesses the DOM should be done after DOM ready. Even if this isn't the issue, this is a common problem when people are new to JavaScript or jQuery.
Most jQuery code is usually found within this ready function: http://api.jquery.com/ready/.
For example, your code should be:
<script type="text/javascript">
$(document).ready(function() {
var canvas = getElementById("draw_area");
var context = canvas.getContext('2d');
var map = new Image();
map.src = "./imgs/home_screen1.png";
map.onload = function (){
context.drawImage (map, 0, 0);
};
});
</script>
精彩评论