[英]Clicking on link inside dropdown menu doesn't work
我有一個dropdown
菜單工作正常,但當我在dropdown
菜單中添加一個鏈接時,該鏈接不起作用。
檢查這里的小提琴,然后嘗試點擊link2和google
鏈接; 這是google
鏈接不起作用。
HTML
<div class="menu">
<div class="link">
<a href="#">Link 1</a>
<div class="dropdown">
Content for dropdown 1
</div>
</div>
<div class="link">
<a href="#">Link 2</a>
<div class="dropdown">
<a href="http://google.com">Google</a>
</div>
</div>
</div>
JQUERY
$('.link a').on("click", function(e){
e.preventDefault();
$(this).parent('.link').siblings().children('.dropdown').fadeOut();
$(this).siblings('.dropdown').fadeToggle();
});
$(document).mouseup(function (e)
{
var container = $(".dropdown");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.hide();
}
});
CSS
.link {
display: inline-block;
position: relative;
float: right;
}
.link a {
padding: 10px;
}
.link .dropdown {
display: none;
position: absolute;
top: 20px;
right: 0px;
color: white;
background: #999;
height: 200px;
width: 200px;
padding: 20px;
border: 1px solid red;
}
http://jsfiddle.net/abLku7e1/2
不知道怎么解決這個問題?
提前致謝
e.preventDefault();
的問題,這是對.link a
是所有 a
的decendents .link
。 使用.link > a
作為父級鏈接。
>
指直接孩子。
嘗試這個:
$('.link > a').on("click", function(e){
e.preventDefault();
$(this).parent('.link').siblings().children('.dropdown').fadeOut();
$(this).siblings('.dropdown').fadeToggle();
});
您只想定位.link的直接后代。
我有一個非常相似的問題。 我的CSS菜單有:
<ul>
<li><a href="#internal link"> Working </a></li>
<li><a href="http://external link"> Not working </a></li>
</ul>
和你一樣,我的javascript使用了e.preventDefault();
單擊后關閉菜單,對於外部鏈接,它將關閉菜單而不實際轉到該外部鏈接。
我通過添加跨度來解決它:
<ul>
<li><a href="#internal link"> Working </a></li>
<li> <span> <a href="http://external link"> </span> Now its working </a></li>
</ul>
將JS代碼更改為僅作用於第一個鏈接而不是所有子鏈接(如下所示)
$('.link>a').on("click", function(e){
e.preventDefault();
$(this).parent('.link').siblings().children('.dropdown').fadeOut();
$(this).siblings('.dropdown').fadeToggle();
});
$(document).mouseup(function (e)
{
var container = $(".dropdown");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.hide();
}
});
注意鏈接>平均只有第一級
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.