Select an item from an ul list of html

0

Good friends, I'm new to this and I want to see if you can help me, I'm doing a project where I must select from an UL list an element and depending on the selected element execute some actions.

<ul>
  <li>Accion 1</li>
  <li>Accion 2</li>
  <li>Accion 3</li>
</ul> 

Selected item

If I select the action 1 .....

If I select the action 2 ....

If I select the action 3 .....

Thanks for the help you can give me

    
asked by José Martínez 19.03.2017 в 21:54
source

2 answers

2

You can do that with jQuery , which gives you great possibilities to change the contents of your page interactively without having to refresh it.

In the example jQuery listens to the clicks of each li element within the ul of the class menu and through this (current element) gets the id of that element and shows it in a div that has id resultado .

jQuery gives you enormous possibilities to do that and more.

Sample code:

$(function(){ 
   $('ul.menu li').click(function(e) 
   { 
       $( "#resultado" ).text( "Seleccionaste: "+this.id);
       /* Aquí si quieres lanzar más acciones de acuerdo al li
           seleccionado puedes implementar un if then else
           u otra estructura de condicionales */
   });
});
<script   src="https://code.jquery.com/jquery-3.2.0.min.js"></script>

<ul class="menu">
    <li id="Accion 1"><a href="#" >Acción 1</a></li>    
    <li id="Accion 2"><a href="#" >Acción 2</a></li>    
    <li id="Accion 3"><a href="#" >Acción 3</a></li>    
</ul>
<hr />
<div id="resultado"></div>
    
answered by 19.03.2017 / 22:58
source
1

You can also do it by writing event handlers for the onclick of each item in the list:

<!DOCTYPE html>

<html>
    <head>
        <title>Acciones</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <style type="text/css">
          li:hover {
              background-color:  blue;
              color:  azure;
          }
        </style> 

        <script type="text/javascript">
          function accion1(){
            alert("Acción 1 pulsada");
          }
          function accion2(){
            alert("Acción 2 pulsada");
          }
          function accion3(){
            alert("Acción 3 pulsada");
          }

        </script>  
    </head>
    <body>
      <ul>
        <li onclick="accion1()">Acción 1 </li>
        <li onclick="accion2()">Acción 2 </li>
        <li onclick="accion3()">Acción 3 </li>        
      </ul>
    </body>
</html>
    
answered by 20.03.2017 в 03:01