我正在尝试使整个 DIV 可点击并使其正常工作。但是,我想对下拉菜单进行异常(exception)处理。单击此下拉按钮
不应打开next.html
。它当前打开下拉菜单,但也会快速打开 next.html
。我该怎么办?
Demo: https://jsfiddle.net/40wntLyo/
<div class="project__body" onclick="location.href='next.html';">
<div class="row">
<div class="col-10">
<h1>Title of the DIV</h1>
</div>
<div class="col-2 text-right">
<div class="dropdown">
<button type="button" class="dropdown-btn dropdown-toggle" data-toggle="dropdown">Menu</button>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" href="#">Edit</a>
<a class="dropdown-item" href="#">Delete</a>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<p>There's more content here in this div. There's more content here in this div. There's more content here in this div. </p>
</div>
</div>
最佳答案
下面的代码片段应该可以工作
将点击事件移至父下拉容器,这也将阻止点击下拉项时的重定向
$('.dropdown').click(function(event) {
$(this).children(".dropdown-menu").toggle()
event.stopPropagation();
})
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<div class="project__body" onclick="location.href='next.html';">
<div class="row">
<div class="col-10">
<h1>Title of the DIV!</h1>
</div>
<div class="col-2 text-right">
<div class="dropdown">
<button type="button" class="dropdown-btn dropdown-toggle" data-toggle="dropdown">Menu</button>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" href="#">Edit</a>
<a class="dropdown-item" href="#">Delete</a>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<p>There's more content here in this div. There's more content here in this div. There's more content here in this div. </p>
</div>
</div>
关于javascript - 使整个 DIV 可点击(下拉列表除外),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56307303/