检测点击<a> in div

时间:2017-03-17 15:08:29

标签: javascript jquery html

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.

6 个答案:

答案 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的直接后代锚点。您的代码应如下所示:

&#13;
&#13;
$(".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;
&#13;
&#13;

答案 2 :(得分:1)

尝试:

&#13;
&#13;
$("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;
&#13;
&#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")