Div with Onclick but not in its jquery elements

3

I have a div and in it some elements, this div needs to be clickable and that its 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, function of the element but also called the function of the 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");
        });
    
asked by anonymous 04.12.2018 / 01:20

1 answer

4

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

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

.stopPropagation() prevents 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><divclass="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>
    
04.12.2018 / 01:32