如何使用JavaScript定位模板中包含的元素?

时间:2018-09-18 12:20:03

标签: javascript php

<script type="text/html" id="tmpl-wp-travel-itinerary-items">
    <div class="panel-wrap panel-wrap-itinerary">
        <label><?php esc_html_e( 'Etape', 'wp-travel' ); ?></label>
        <select id="selectjs"></select>
     </div>
</script>
getElementById() 上的

selectjsnull;可以在脚本标签中通过其元素定位此元素吗?

1 个答案:

答案 0 :(得分:0)

有一种方法-最终-使用id模板方法通过其<script>属性检索元素;但是它很复杂,据我所知,它需要创建一个临时元素来保存模板内容,然后查询该元素:

// retrieve the innerHTML of the template, using the id of the template itself:
let templateSource = document.getElementById('tmpl-wp-travel-itinerary-items').innerHTML,

// creating an element to hold, and from which to retrieve, that content:
    template = document.createElement('div');

// assigning the content of the template as the innerHTML of the created-element:
template.innerHTML = templateSource;

// finally, retrieving the <select> element via its id, from the
// created-element and Element.querySelector():
let selectElement = template.querySelector('#selectjs');

// logging the selectElement to the console:
console.log(selectElement);
<script type="text/template" id="tmpl-wp-travel-itinerary-items">
  <div class="panel-wrap panel-wrap-itinerary">
    <label><?php esc_html_e( 'Etape', 'wp-travel' ); ?></label>
    <select id="selectjs"></select>
  </div>
</script>

JS Fiddle demo

但是,有一种使用HTML <template>元素的方法稍微容易一些:

// retrieving the <template> via its id:
let template = document.querySelector('#templateContent'),

  // accessing the <select> from the content property
  // of the <template>:
  select = template.content.querySelector('select');

// logging the <select> element to the console:
console.log(select);
<template id="templateContent">
  <div class="panel-wrap panel-wrap-itinerary">
    <label></label>
    <select id="selectjs"></select>
  </div>
</template>

JS Fiddle demo

参考文献: