jQuery在< li>上不起作用元素,但不是< a>元素 [英] jQuery not works on <li> elements, but not <a> elements
问题描述
当单击具有特定ID的项目时,我会运行一些jQuery代码.当ID是<li>
元素的一部分时有效,但是当它在<a>
元素中时则无效.为什么会这样呢?我想使用一个,因为如果用户关闭了JavaScript,它可以实现一些目标.
I have some jQuery code that runs when an item with a certain ID is clicked on. It's working when the ID is part of an <li>
element, but not when it's in an <a>
element. Why would this be? I'd like to use an as it allows me to achieve some stuff if the user has JavaScript turned off.
编辑:防止默认值或返回false似乎没有任何作用.
Neither preventdefault or return false seem to make any difference.
下面的HTML和代码:
HTML and Code below:
<li><a id="OfficeNav-Bath" class="first" href="#bath">Bath</a></li>
编辑:如果在<a>
元素中未指定HREF,则可以使用该功能.
It works if there's no HREF specified in the <a>
element.
$(function() {
$("#OfficeNav-Bath").click(function(){
$('.office').removeClass('visible');
});
});
有人知道为什么会这样吗?预先感谢.
Any idea why this would be? Thanks in advance.
推荐答案
我认为与<a>
标记一起使用时,您并没有阻止默认事件,因此请尝试执行以下操作:
i think you are not preventing the default event when using with <a>
tags, so try doing:
$(function() {
$("#OfficeNav-Bath").click(function(e){
e.preventDefault();
$('.office').removeClass('visible');
});
});
这篇关于jQuery在< li>上不起作用元素,但不是< a>元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!