简体   繁体   English

HTML模板-分配html数据

[英]HTML template - assigning html data

I am using HTML for the first time in combination with an AJAX call. 我是第一次结合AJAX调用使用HTML。 Is it possible assign html data to a div using JavaScript? 是否可以使用JavaScript将html数据分配给div?

I have the following: 我有以下内容:

<template class="template result student">
    <div class="result student" data-category="student">
        <div class="box name">
            <span class="name">John Smith</span>
            <br />
            <span class="category">Student</span>
        </div>
    </div>
</template>

And JS 和JS

const studentTemplate = 
    document.querySelector(".template.result.student"),
    category = studentTemplate.dataset.querySelector(".result.student"),
    studentName = studentTemplate.content.querySelector(".box.name .name"),
    date = studentTemplate.content.querySelector(".box.dob .date");

   category.textContent    = "student";
   studentName.textContent = "student name";

So as you can see I am trying to set date-student in the template via JS. 如您所见,我正在尝试通过JS在模板中设置日期学生。 But I get 但是我明白了

studentTemplate.dataset.querySelector is not a function

Question is, what is correct way of doing this? 问题是,这样做的正确方法是什么? Setting the content works fine 设置内容效果很好

You need to use the content property to access content of the template. 您需要使用content属性来访问模板的内容。

The dataset property is for accessing data- html attributes and would be followed with the name of the attribute, as in dataset.category . dataset属性用于访问data- html属性,后跟该属性的名称,如dataset.category As the error states, querySelector() is not a valid method on the data object returned from the dataset property. 由于错误状态, querySelector()对从dataset属性返回的数据对象不是有效的方法。

 const studentTemplate = document.querySelector(".template.result.student"); var category = studentTemplate.content.querySelector(".result.student"); var studentName = studentTemplate.content.querySelector(".box.name .name") var dte = studentTemplate.content.querySelector(".box.dob .date"); // Modify the text content of the elements category.textContent = "teacher"; studentName.textContent = "teacher name"; // Modify the data-category attribute value of the the div category.dataset.category = "teacher"; console.log(category); 
 <template class="template result student"> <div class="result student" data-category="student"> <div class="box name"> <span class="name">John Smith</span> <br /> <span class="category">Student</span> </div> </div> </template> 

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

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