jqueryonclickhandlebars.jsdynamic-list

Open link on clicking dynamic objects in a list


I have a code in Handlebars that generates dynamic list.

<ul id="expList">
{{#each hierarchy}}
    <li class="index">{{@key}}
        <ul>
            {{#each this}}
                <li class="country">{{@key}}
                    <ul>
                        {{#each this}}
                            <li class="cluster">{{@key}}
                                <ul>
                                    {{#each this}}
                                        <li class="farm">{{@key}}
                                        </li>
                                    {{/each}}
                                </ul>
                            </li>
                        {{/each}}
                    </ul>
                </li>
            {{/each}}
        </ul>
    </li>
{{/each}}
</ul>

Now i want a webpage to open when i click an element. The URL will be a combination of the element clicked and its parent.

Without having an id because of being dynamic, how should i attach an onClick event in jQuery.

Thanks in advance.


Solution

  • You can use on() : http://api.jquery.com/on/

    $(document).on("click", ".cluster", function(e) {
       // you can get your clicked element here
       console.log("event"); 
    });
    

    EDIT

    So for a farm :

    $(document).ready(function() {
       $(document).on("click", ".farm", function(e) {
         var idfarm= $(this).attr('data-id');
         var idcluster= $(this).parent().parent().attr('data-id');
         
         $("#result").html(idfarm +"|"+ idcluster);
         console.log("event"); 
         
         // This cant work in stackoverflow sandbox allow-popups permission is not set
         window.open('http://localhost:8000?farm='+idfarm+'&cluster='+idcluster,'GoogleWindow', 'width=800, height=600');
         });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <li class="cluster" data-id="key cluster">key cluster
         <ul>      
           <li class="farm" data-id="key farm">Key farm</li>
           </ul>
       </li>
       
    <div id="result"></div>