-->

OnsenUI - Select element with jQuery/JS (ons-templ

2019-09-14 00:04发布

问题:

I’m brand new to OnsenUI and so far I’m really enjoying the look and feel of it all. I’m using it with plain JS and a little jQuery.

My issue is: I cannot select anything (ID, Class etc.) using JS or jQuery while I’m using ons-template.

When I remove this I don’t have any issues, buuuut I’m using ons-splitter as my navigation method. (note: I've also tried tabs etc)

Is there something I’m doing wrong?

<ons-splitter>
  <ons-splitter-side id="menu" side="left" width="220px" collapse swipeable>
    <ons-page>
    sidebar content etc...
    </ons-page>
  </ons-splitter-side>
  <ons-splitter-content id="content" page="main.html"></ons-splitter-content>
</ons-splitter>

<!-- I want to select the ons-list-item #book with jQuery -->
  <ons-template id="main.html">
    <ons-page>
      <ons-toolbar>
        <div class="left">
          <ons-toolbar-button onclick="fn.open()">
            <ons-icon icon="md-menu"></ons-icon>
          </ons-toolbar-button>
        </div>
        <div class="center top-bar-title">Title</div>
      </ons-toolbar>
      <ons-list>
        <ons-list-item id="book">Books</ons-list-item>
      </ons-list>
    </ons-page>
  </ons-template>

<script>   
    $("#book").click(function(){
        alert("TEST");
    });  
</script>

Thanks for any help!

回答1:

The problem here is that when the script is being executed, the template is still not loaded into the splitter-content, thus there is no element with the id "book".

The solution is to add the event listener on the initialization of the main.html page. That way, you are sure that the template is loaded and you can select any of the ids present on that template.

NOTE: Make sure to add an id on the <ons-page> element.

How to add a listener or call a function on the initialization of a page:

<ons-splitter>
  <ons-splitter-side id="menu" side="left" width="220px" collapse swipeable>
    <ons-page>
    sidebar content etc...
    </ons-page>
  </ons-splitter-side>
  <ons-splitter-content id="content" page="main.html"></ons-splitter-content>
</ons-splitter>

<!-- I want to select the ons-list-item #book with jQuery -->
  <ons-template id="main.html">
    <ons-page id="main">
      <ons-toolbar>
        <div class="left">
          <ons-toolbar-button onclick="fn.open()" tappable>
            <ons-icon icon="md-menu"></ons-icon>
          </ons-toolbar-button>
        </div>
        <div class="center top-bar-title">Title</div>
      </ons-toolbar>
      <ons-list>
        <ons-list-item id="book" tappable>Books</ons-list-item>
      </ons-list>
    </ons-page>
  </ons-template>

<script>

    document.addEventListener("init",function(event){

        if(event.target="main"){
               $("#book").click(function(){
                    alert("TEST");
                });  
        }
    });

</script>