简体   繁体   中英

javascript click event on dropdown menu

an application I have four dropdwon -menu where one of these is filled by selecting an earlier ... this is filled in automatically ... does not respond to click event
I have searching by answers about creating a dinamic UL LI itens and found this:

    function getModelos(response) 
    {
        var obj = JSON.parse(response);
        try
        {   
            var ul = document.getElementById("modelo");
            var modelos = obj.modelos;
            var x = document.getElementById("modelo");

            while(x.length > 0)
            {
                x.remove(0);
            }
            for(i=0;i<modelos.length;i++)
            {
                var li = document.createElement("li");
                var a = document.createElement("a");
                a.appendChild(document.createTextNode(modelos[i].modelo));
                a.setAttribute("href","#");
                a.setAttribute("data-value",modelos[i].id+",.modelo");
                li.appendChild(a);
                ul.appendChild(li);
            }
      }
      catch(err)
      {
          alert("ERRO: "+err);
      }
  }

also I have found a click event delegating:

    $(".dropdown-menu li a").click(function()
    {
        var selText = $(this).text();
        $(this).parents('.dropdown').find('.dropdown-toggle').html(selText+'                             <span class="caret"></span>');
        var valor = $(this).data('value');
        var options = valor.split(",");
        $(this).parents(".dropdown").find(options[1]).val(options[0]);
        if(options[1] == ".marca")
        {
            pedeModelos(selText);
        }
    });

all dropdowm-menus previously defined response to click on LI, but this dropdown dinamic created don't

I'm new to javascript/Bootstrap/JQuery, I need a way to follow, I will apreciate any help. thanks

The issue is how you are delegating the click event. If your delegation is outside the event which is creating the dynamic elements than its not going to work. Your reference to the click event should happen in the same function where you are generating the dynamic html.

For example :

<input type="button" id="btn" value="GenerateHTML"/><br/>
<div>       
</div>

$("#btn").click(function()
{
    $("div").append("<ul class='dropdown-menu'><li><a href='#'>1</a></li><a href='#'>2</a></ul>");
    $(".dropdown-menu").find("li a").click(function()
    {
        alert();
    });

});

http://jsfiddle.net/pkhout3x/

Like this:

$(".dropdown-menu").on("click","li a",function() {blah});

Read about Direct and delegated events

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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