Detect click on li, not on div

0

I have an application that displays a menu if we right click on the central div (#body), in this div there are files represented in a list <li> , each <li> has as id #fichero . My problem is that sometimes there are no files and if I click the menu is displayed (since I right click on #cuerpo ).

This I have programmed it like this:

  $("#cuerpo").bind("contextmenu", function(e){

...despliego menu...

  });

Easy solution? change #body by #file, but it does not work for me.

Does anyone give me the solution? What am I doing wrong?

Thanks

    
asked by Fabián Moreno 13.06.2018 в 14:11
source

2 answers

1

The id must be unique, and you say that all <li> elements have the same. Put different ids and a common class and detect the click on the class.

Example:

<div id="midiv">
  <li class="clase-li" data-id="1"></li>
  <li class="clase-li" data-id="2"></li>
  <li class="clase-li" data-id="3"></li>
</div>

And then you detect the click

$(".clase-li").click(function (){
  alert($(this).data("id"));
});
    
answered by 13.06.2018 в 14:24
0

You commented that within #body you have something related to php. Without knowing in detail how that code is implemented (it would be very good if you could copy a more detailed fragment of the code as indicated in the first comment), you may have a problem of bindeo. If the .bind is executed before the li class="class-li" elements exist, the bind will not work, since you can not assign that handler to any element.

Meanwhile, what you could do to get through is a simple but effective workaround: within the bind, implement a logic to show or not depending on the number of li elements that the list has. That is:

$('#cuerpo').bind('contextmenu', function(e) {
  if(numeroElementosLista > 0) {
     mostrarMenuContextual();
  }
});

That way, when there's nothing on the list, it will not do anything. It is not the most elegant but functional solution that will allow you not to be blocked while waiting for a solution.

    
answered by 18.06.2018 в 15:23