I have a balise "a" inside a div block, and I want to detect the click event when the user click on the button represented by the balise <a>
. this is my code:
<div class="top-bar-left">
<ul class="menu BreadCrumbs">
<li>
<a href = "link" class="button" data-clicklistener />
</li>
</ul>
</div>
to detect the click event on <a href = "link" class="button" data-clicklistener />
I have tired this code JS:
$(".top-bar-left > .menu.BreadCrumbs > a.button").on('click', function () {
var confirmationDialog = confirm("Are you sur ?");
});
but this code doesn't work.
答案 0 :(得分:1)
您的jQuery选择器是错误的。使用>
运算符意味着它必须是下一个孩子,而不是任何孩子。
$(".top-bar-left .menu.BreadCrumbs a.button").on('click', function () {
var confirmationDialog = confirm("Are you sur ?");
});
或
$(".top-bar-left > .menu.BreadCrumbs > li > a.button").on('click', function () {
var confirmationDialog = confirm("Are you sur ?");
});
答案 1 :(得分:1)
首先,您应该使用event.preventDefaul()
来阻止锚点的默认操作。这里的主要问题是您正在尝试选择不存在的.menu.BreadCrumbs
的直接后代锚点。您的代码应如下所示:
$(".top-bar-left > .menu.BreadCrumbs > li > a.button").on('click', function(e) {
e.preventDefault();
confirm("Are you sure ?");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top-bar-left">
<ul class="menu BreadCrumbs">
<li>
<a href="#" class="button" data-clicklistener>Link</a>
</li>
</ul>
</div>
&#13;
答案 2 :(得分:1)
尝试:
$("a.button").on('click', function (e) {
var confirmationDialog = confirm("Are you sure ?");
if(!confirmationDialog){
e.preventDefault();
console.log("Clicked no :(");
}else{
console.log("Clicked yes :)");
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top-bar-left">
<ul class="menu BreadCrumbs">
<li>
<a href = "link" class="button"> Link</a>
</li>
</ul>
</div>
&#13;
答案 3 :(得分:0)
这应该这样做:
$('.top-bar-left').on('click', '.button', function () {
var confirmationDialog = confirm("Are you sur ?");
});
答案 4 :(得分:0)
这是因为此选择器$(".top-bar-left > .menu.BreadCrumbs > a.button")
希望找到锚标记为.BreadCrumbs
的直接子标记,并且它实际上嵌套在li
改为使用
$(".top-bar-left > .menu.BreadCrumbs a.button")
将查看所有孩子
或者更明确一点,你可以使用
$(".top-bar-left > .menu.BreadCrumbs > li > a.button")
答案 5 :(得分:0)
将$(".top-bar-left > .menu.BreadCrumbs > a.button")
更改为$(".top-bar-left .menu.BreadCrumbs a.button")