Div with Onclick but not in its jquery elements

Asked

Viewed 646 times

3

I have a div and in it some elemtos, this div needs to be clickable and that your click will do an action, but, its elements that some are Buttons also have own actions,what happens is that when I click on the elements, it is called the function of the element but also called the function of div.

DIV example:

    <div class="detalhes" id="2">
        teste

            <button class="Remove" remove_item="a" >
                texto
            </button>
    </div>

    <div class="detalhes" id="3">
        teste

            <button class="Remove" remove_item="a" >
                texto
            </button>
    </div>

DIV function:

    $(".detalhes").click(function()
    {
        var reg = $(this).attr("id");

    });

Element:

        $('body').on("click", ".Remove", function()
        {
            var Remove_item     = $(this).attr("Remove_item");
        });

1 answer

4


You need to use .stopPropagation() in the parent element of the button, in the case of the .detalhes. So, just change the click selector on .Remove for .detalhes instead of body, and catch the event by placing a parameter in the function:

$('.detalhes').on("click", ".Remove", function(evt){
  evt.stopPropagation();
  var Remove_item     = $(this).attr("Remove_item");
});

The .stopPropagation() avoids the Bubbling, which is when an event of a child element also triggers events in the parent element.

Example:

$(".detalhes").click(function(){
  var reg = $(this).attr("id");
  console.log(reg);

});

$('.detalhes').on("click", ".Remove", function(evt){
  evt.stopPropagation();
  var Remove_item     = $(this).attr("Remove_item");
  console.log(Remove_item);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="detalhes" id="2">
   teste
   <button class="Remove" remove_item="a" >
      texto
   </button>
</div>

<div class="detalhes" id="3">
   teste
   <button class="Remove" remove_item="b" >
   texto
   </button>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.