jQuery mouseover 不适用于 li 元素
我正在尝试制作一个基于 ul 元素的菜单,该元素将在链接下方显示链接描述。
到目前为止,我有以下代码(稍微简化了)
echo '
<script>
$("#menu_1").mouseover(function() {
$("#description").replaceWith("test");
});
</script>
<ul class="menu_top">
<li id="menu_1"><a href = "#">Test</a></li>
</ul>
<div id="description" class="menu_desc">
</div>
';
但是,每次我将鼠标移到 li 元素上时,都没有任何反应。
有谁知道我做错了什么?
I'm trying to make a menu based on an ul element that will show the link description underneath the link.
So far, I have the following code (simplified a little)
echo '
<script>
$("#menu_1").mouseover(function() {
$("#description").replaceWith("test");
});
</script>
<ul class="menu_top">
<li id="menu_1"><a href = "#">Test</a></li>
</ul>
<div id="description" class="menu_desc">
</div>
';
However, everytime I move the mouse over the li element, nothing happens.
Does anyone know what I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要确保您的事件分配发生在文档加载完成后,否则您的鼠标悬停事件也没有任何附加内容:
这是一个工作演示: http://jsfiddle.net/2mWb3/
You need to make sure that your event assignment happens after the document has finished loading, otherwise your mouseover event has nothing to attach too:
Here's a working demo: http://jsfiddle.net/2mWb3/
当您运行此代码时,
#menu1
尚未在 DOM 中。将其更改为
,以便您的代码在
document.ready
事件上运行。#menu1
is not yet in the DOM when you run this code..change it to
so that your code runs on
document.ready
event.Javascript 代码在遇到时执行。这可能发生在文档实际准备好之前。在您的情况下,您尝试在
#menu_1
元素实际存在于文档中之前选择它。因为您几乎肯定希望所有 jQuery 代码在文档准备好后运行,所以 jQuery 为您提供了一个快捷方法:Javascript code is executed as it is encountered. This might happen before the document is actually ready. In your case, you're trying to select the
#menu_1
element before it actually exists in the document. Because you almost certainly want all your jQuery code to run after the document is ready, jQuery provides a shortcut method for you: