jQuery没有参考
我有一个链接。我需要为点击元素编写一个点击函数。 所以我写了这样的代码。
<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>
我写了一个js文件,里面写了很多函数。
$('.tabCon > ul > li > a').click(function() {
alert('Link Clicked !');
});
但是当我在 head 部分中声明此 JavaScript 文件的引用时,这不会起作用。
当我在元素下方或 body 结束标记之前声明时,此有效
为什么会发生这种情况?还有其他办法吗?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果将 jQuery 代码放在 head 部分,请确保在 document.ready 处理程序中执行 jQuery 代码,否则当您尝试将单击处理程序附加到某个元素时,DOM 可能尚未加载并准备好进行操作:
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:
因为如果将其添加到 head 中,则该元素尚未在 DOM 中创建,因此您无法通过 JavaScript 将其作为对象访问!
试试上面的方法吧!
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!
Try the above!
当解析器位于 head 时,该元素不存在于 DOM 中,但是当它(javascript 解析器)到达结束 body 标记时,它就存在了。因此。
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.
确保您的 document.ready 事件中有 jQuery 调用。
基本上,如果您在 HEAD 块中编写 jQuery,请将整个内容包装在
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
你有没有把这个函数 $("...").click(...);在 $(function(){ ... } 块中,以便在加载页面时它处于活动状态。如果没有,这是正常的,这将不起作用。尝试将您的函数放在 $(function(){ 中。 .. } 块,它会起作用
。
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.