开发者

jQuery has no reference

开发者 https://www.devze.com 2023-03-08 09:48 出处:网络
I have a link. I need to write a click function for theelement on click. so i have written a code like this.

I have a link. I need to write a click function for the element on click. so i have written a code like this.

<div class="tabCon">
  <ul>
    <li><a href="javascript:void(0);" id="Overview">Overview</a></li>
    <li><a href="javascript:void(0);" id="ProjDet">Project Details</a></li>
    <li><a href="javascript:void(开发者_运维知识库0);" id="Directions">Directions</a></li>                                         
  </ul>
<div>

I have written a js file in which i have written so many functions.

$('.tabCon > ul > li > a').click(function() { 
   alert('Link Clicked !');
});

But this wont works when i declare the reference for this JavaScript file in the head section.

This works when i declare below the element or before the closing of body tag

why this happens ? is any other ways ?


Make sure that you are executing your jQuery code inside a document.ready handler if you put it in the head section otherwise the DOM might not yet be loaded and ready to be manipulated when you try to attach a click handler to some element:

$(function() {
    $('.tabCon > ul > li > a').click(function() { 
       alert('Link Clicked !');
    });
});


Because if you add it in the head, the element hasn't been created in the DOM yet, so you cannot access it as an object via JavaScript!

$(document).ready(function () {
  $('.tabCon > ul > li > a').click(function() { 
   alert('Link Clicked !');
  });
});

Try the above!


The element doesn't exist in the DOM when the parser is in the head, but by the time it (the javascript parser) reaches the closing body tag, it does. That is why.


Make sure you've got the jQuery call inside your document.ready event.

Basically, if you're writing jQuery in the HEAD block, wrap the whole thing in

$(function() {

//jquery code goes here

});


Do u have put this function $("...").click(...); in a $(function(){ ... } block so it's active when the page is loaded. If not, this is normal that this won't work.. Try to put your function in a $(function(){ ... } block and it will works.

Pad.

0

精彩评论

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