【问题标题】:stop click event propagation when clicked inside anchor tag on a div在 div 上的锚标记内单击时停止单击事件传播
【发布时间】:2014-11-17 05:29:34
【问题描述】:

描述:

我有以下 HTML

<a href = "go some where">

<div onclick = "myfunc1(....)">CLICK ME A</div>

<div onclick = "myfunc2(....)">CLICK ME B</div>

</a>

现在,当我单击第一个 div 时,锚标记会被触发,第二个 div 也是如此。我希望能够单击锚标记内的任何 div,它应该只调用分配给它的函数 ...

当且仅当我不点击任何 div 但整个其他区域锚标记具有然后它应该带我到页面 href 有...

我尝试了什么:

$(".add_this_person").on("click", "a", function (e) {
    e.preventDefault();
} ); // where add_this_person is a class of both divs

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    你可以试试这个:-
    class 添加到 div 并更改 jQuery 代码如下:-

    $(".add_this_person").on("click", "a", function (e) {
      e.preventDefault();
      if($(e.target).is('.first'))
      {
         alert("A");
      }else if($(e.target).is('.second'))
      {
        alert("B");
      }else{
        window.location=$(this).attr('href');
      }
     }); 
    

    Demo

    【讨论】:

      【解决方案2】:

      您的尝试没问题,但您可以充分利用 jQuery,而无需在 div 中使用“onclick”事件。只需分配一个类并创建一个类事件,该事件将为具有给定类的所有元素触发,并将目标函数存储在一个额外的属性中......

      只需将您的 div 标签与操作“my-action”一起放置,并将目标函数存储在 以函数名作为目标的 HTML 数据中继“函数”。

      <div class="my-action" data-function="myAction1" >CLICK ME A</div>
      
      <div class="my-action" data-function="myAction2">CLICK ME B</div>
      
      
      <script type="text/javascript">
          $(document).ready(function() {
      
              //Declare your functions here, add them to window[] array...
              window.myAction1 = function() {
                  alert("A");
              }
      
              window.myAction2 = function() {
                  alert("B");
              }
      
              //This will trigger whenever an element with class "my-action" is clicked...
              $(document).on("click", ".my-action", function (e) {
                  //Just read the function name from data-function and assign it from window[] array
                  var targetFunction = window[$(this).data("function")];
      
                  //And execute it, done!
                  targetFunction();
              });
          });
      </script>
      

      创建了一个有效的小提琴...... http://jsfiddle.net/Lnnffcx5/

      【讨论】:

        猜你喜欢
        • 2023-03-06
        • 1970-01-01
        • 1970-01-01
        • 2017-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-07
        • 1970-01-01
        相关资源
        最近更新 更多