如何获取模板html中的元素? [英] How to get element in template html?
问题描述
我正在开发一个 Electron
应用,其中 index.html
导入一个 search.html
:
I am developing an Electron
app, in which the index.html
imports a search.html
:
<link rel="import" href="search.html">
在search.html
中,我创建了一个id为searchBtn
的按钮.
And inside the search.html
, I create a button whose id is searchBtn
.
然后,在redenerer.js
中,我尝试获取searchBtn
:
Then, in the redenerer.js
, I try to get the searchBtn
:
var link = document.querySelector('link[rel="import"][href="search.html"]');
var content = link.import.querySelector('template');
console.log(content);
var searchBtn = content.querySelector('#searchBtn');
console.log(searchBtn);
第一个日志的输出是预期的,但是 searchBtn
的第二个日志总是null.
The output of the first log is expected, but the second log for searchBtn
is always null.
我的代码有问题吗?如果是这样,如何正确获取模板html中的元素?
Is there any wrong with my code? If so, how to obtain the element in template html correctly?
输出如下:
我注意到模板中有一个 document-fragment
.
I notice that there is a document-fragment
inside the template.
推荐答案
在模板 content
属性上运行 querySelector
函数.
Run the querySelector
function on the templates content
property.
var link = document.querySelector('link[rel="import"][href="search.html"]');
var templateContent = link.import.querySelector('template');
console.log(templateContent);
var searchBtn = templateContent.content.querySelector('#searchBtn');
console.log(searchBtn);
更多关于文档片段.
更多关于模板.
工作沙箱;
这篇关于如何获取模板html中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!