Search code examples
javascriptjqueryangularjsdomsinglepage

How to avoid jQuery Operation Conflict with 2+ templates In Single-Page Application


I build a Single-Page Application for ERP-like system with MVVM

there is one template A which include JQ operations like $("#xxx") ,some JQ pluigns like bootsrap modal and fineuploader also need attribute id to locate its modal and sub-template,

<a href="#myModal" role="button" class="inline btn" data-toggle="modal">Select</a><br>
<!-- bootstrap modal use #id to find its modal template -->

Now I want to load template A twice (A1,A2) in one-page 'index.html',however I suffer JQ operation conflict ($("#xxx") in A1 return elements in A1 and A2 ,but I only need that in A1)

So,How to seperate A1 and A2 when I use Jquery?!

[it's a good idea to use $(#id.class) for find element outside(index.html) not template inside(JQ operations are in A) because A1,A2 templates share the same $(#id.class) and finally return two JQ objects. also using template engineer lead to difficulty of debugging this template because it's a complicated page]


Solution

  • A single page cant have any two elements with same id, like #xxx. Use class instead of id.

    <div class="xxx">A</div>
    

    EDIT:
    If you cant simply change id to class, you could use some js template to generate a dynamic id or a dynamic data-target.

    http://getbootstrap.com/javascript/#modals-sizes

    <!-- dynamic id -->
    <a href="#myModal<%= count %>" data-toggle="modal">Select</a>
    <div id="myModal<%= count %>" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">...</div>
    
    <!-- dynamic data-target -->
    <a data-target"myModal<%= count %>" data-toggle="modal">Select</a>
    <div class="modal fade myModal<%= count %>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">...</div>