简体   繁体   English

访问导入的本地HTML文件的DOM

[英]Access DOM of an imported local HTML file

I'm working on a project in which I would like to import a locally stored HTML template using JavaScript. 我正在一个项目中,我想使用JavaScript导入本地存储的HTML模板。

This template will be dynamically filled with datas that I get by accessing a website REST API. 该模板将动态填充我通过访问网站REST API获得的数据。

This is an example of what I want to do : 这是我想做的一个例子:

index.html : index.html:

<!DOCTYPE html>
<html>
<head>
    <title>My Site</title>
</head>
<body>
    <div id="loaded-content">
        <!-- Here will be displayed the template -->
    </div>
</body>
<script type="text/javascript" src="script.js"></script>
</html>

template.html: template.html:

<div id="data">
    <h1 id="data-name">value</h1>
    <p id="first-attribute">value</p>
    <p id="first-attribute">value</p>
    <p id="first-attribute">value</p>
</div>

datas.json: datas.json:

{
    "datas":
    [
        {
            "name": "value",
            "first-attribute": "value",
            "second-attribute": "value",
            "third-attribute": "value"
        },
        {
            "name": "value",
            "first-attribute": "value",
            "second-attribute": "value",
            "third-attribute": "value"  
        }
    ]
}

For each object contained in datas, I want to display the template again. 对于数据中包含的每个对象,我想再次显示模板。

Currently, I load the template using XMLHttpRequest object. 当前,我使用XMLHttpRequest对象加​​载模板。 I can display the content of my template but I can't access to the template's DOM to change the value of its elements. 我可以显示模板的内容,但是无法访问模板的DOM来更改其元素的值。

Which method should I use to correctly load my HTML file ? 我应该使用哪种方法正确加载HTML文件? I'm looking for something in pure Javascript (no jQuery or something). 我正在寻找纯JavaScript的东西(没有jQuery之类的东西)。

Thank you for your help =) 谢谢您的帮助=)

Your immediate problem is that your template as it currently stands will result in multiple elements with the same ID, which isn't allowed. 您的直接问题是,当前的模板将导致多个具有相同ID的元素,这是不允许的。

If you have control of the template, change it to be a more traditional template style where vars are bracketed off rather than relying on HTML IDs. 如果您可以控制模板,则将其更改为更传统的模板样式,其中将括号括起来而不是依靠HTML ID。 So I'd change your template to be: 因此,我将您的模板更改为:

<div>
    <h1>{{name}}</h1>
    <p>{{first-attribute}}</p>
    <p>{{second-attribute}}</p>
    <p>{{third-attribute}}</p>
</div>

This way we can run string replacements via REGEX rather than outputting then interrogating the items by IDs. 这样,我们可以通过REGEX运行字符串替换,而不是通过ID输出然后查询这些项。

Let's say #content is the container element for the templates, data stores your parsed JSON data and template stores the unparsed template string: 假设#content是模板的容器元素, data存储已解析的JSON数据, template存储未解析的模板字符串:

var
cntr = document.querySelector('#content'),
html;

//iterate over data items
data.datas.forEach(function(obj) {

    //grab all var references i.e. {{foo}} and replace them with actual values, if exist
    html = template.replace(/\{\{[^\}]+\}\}/g, function(match) {
        var var_name = match.replace(/^\{\{|\}\}$/g, '');
        return obj[var_name] || '??';
    });

    //append the readied HTML to the content container
    cntr.innerHTML += html;
});

This is an example. 这是一个例子。 You can use a JSON parser to get the data in the format you need. 您可以使用JSON解析器以所需的格式获取数据。 So here is what you do: create a dummy <div> DOM element to push later, use replace function to replace val with the value of the data variable. 因此,您可以执行以下操作:创建一个虚拟<div> DOM元素以稍后推送,使用replace函数将val替换为data变量的值。 Then finally append this to the HTML's div element. 然后,最后将其附加到HTML的div元素。 If you got the data using an XMLHttpRequest , pass on the data to template . 如果使用XMLHttpRequest获得数据,则将数据传递给template Then replace the placeholders value with the data from parsing JSON. 然后,将占位符value替换为解析JSON中的数据。 And use replace method to do so. 并使用replace方法来做到这一点。 It should work fine. 它应该工作正常。

 var template = document.createElement("div"); var data = "Hello world"; template.innerHTML = "<h1>val</h1>"; template.innerHTML = template.innerHTML.replace("val", data); document.getElementById("myDiv").appendChild(template); 
 <div id="myDiv"> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM