开发者

Why the jQuery events are not fired?

开发者 https://www.devze.com 2023-04-11 19:40 出处:网络
I thinkg I doing something wrong, but the events only works if the selector is document. Otherwise, not happens.

I thinkg I doing something wrong, but the events only works if the selector is document. Otherwise, not happens.

HTML

<html>                                                                  
   <head>
       <!-- the libraries references here -->
   </head>                                                                 
   <body>
       <div id="canvas"></div>      
   </body>                                                                 
</html>

Javascript

/* Click on canvas */
canvasClickEvent = function(e){     
    if(e.shiftKey){
        selectedElement = $(this).attr("id");
    }
}

/* Events */
$(document).ready(documentLoadEvent);
$(document).click(canvasClickEvent); //this works, but is wrong
//$("#canvas").click(canvasClickEvent); --this is what I want, but not works
$(document).dblclick(canvasDblClickEvent);

If I replace the document by the div name like $('#canvas').click(canvasClickEvent);, the click event is not called. It's only works if the selector is do开发者_C百科cument, but the element passed to the function always has the attibs like undefined.

What might be happening?


What is happening is that event is attempting to bind the event before the DOM element exists.

If you wrap the events inside of the ready() method you guarantee that the domain exists before your event attempts to bind.

$(document).ready( function ()  {
     $("#canvas").click(canvasClickEvent);
}

The ready() method is dependent on the browsers DOMContentLoaded event which basically means the DOM is completely loaded in the browser, but does not necessarily mean all the media on the page has completely loaded. Once all media is loaded the onLoad browser event fires.


It seems like you put your JavaScript code BEFORE the html code. So, when the JavaScript code runs, the elements to be dealt with is not loaded into the DOM yet. (That's why you got "undefined")

Just put your script AFTER the related HTML code. Or put it inside the pageLoad event:

$(function(){
    ....
})
0

精彩评论

暂无评论...
验证码 换一张
取 消