简体   繁体   English

在div上的锚标记中单击时,停止单击事件传播

[英]stop click event propagation when clicked inside anchor tag on a div

DESCRIPTION : 说明:

I have the following HTML 我有以下HTML

<a href = "go some where">

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

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

</a>

Now when I click the first div the anchor tag gets fired same goes for the second div .. I want to be able to click any div inside the anchor tag and it should just call the function assigned to it ... 现在,当我单击第一个div时,将触发锚标记,第二个div也将被触发。.我希望能够单击锚标记内的任何div,它应该只调用分配给它的函数...

if and only if I dont click on any div but the whole other area anchor tag has then it should take me to the page href has... 当且仅当我不单击任何div但整个其他区域的定位标记都具有时,才应将我带到href具有的页面...

What Have I Tried : 我试过了什么:

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

You can try this:- 您可以尝试以下方法:
Add class to both div and change jQuery code like this:- 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 演示

Your attempt is okay but you can use jQuery full potential without using "onclick" events in the div. 您的尝试还可以,但是您可以使用jQuery的全部功能,而无需在div中使用“ onclick”事件。 Just assign a class and make one class event that will fire for all elements with the given class and store the target function in an extra attribute... 只需分配一个类并创建一个类事件,该事件将针对给定类的所有元素触发并将目标函数存储在额外的属性中...

Simply place your div tags with action "my-action" and store the target function in a HTML data-trunk "function" with function name as target. 只需将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>

Created a Fiddle which works... http://jsfiddle.net/Lnnffcx5/ 创建了一个有效的小提琴... http://jsfiddle.net/Lnnffcx5/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM