【问题标题】:Returning contents of template tag as string将模板标签的内容作为字符串返回
【发布时间】:2015-09-28 22:24:45
【问题描述】:

我想知道是否有一种方法可以获取模板标签中元素的内容并将其作为字符串返回?目前,它似乎正在返回类似于[object document fragment] 的内容,但只需要里面的 html 内容。

function CreateWidget(widget) {
    //Check if browser supports templates
    if ('content' in document.createElement('template')) {
        //Grab the template's content and assign it to a variable so we only have the gut of the template
        var widgetContent = document.querySelector('#panel-template').content //('#panel-template').get(1).setAttribute('id', widget.WidgetCode);
        widgetContent.querySelector('#chart').setAttribute('id', widget.WidgetCode);

        //get the overlay toolbar
        var widgetOverlay = widgetContent.querySelector('.overlayed');
        widgetOverlay.setAttribute('data-render', widget.WidgetCode);
        widgetOverlay.setAttribute('data-chartType', widget.chartType);
        widgetOverlay.setAttribute('data-devID', widget.deviceID);
        widgetOverlay.setAttribute('data-metricType', widget.metricType);
        widgetOverlay.setAttribute('data-title', widget.WidgetName);

        var el = document.importNode(widgetContent, true);
        alert(el);   
    }
}

【问题讨论】:

    标签: javascript jquery dom web-component html5-template


    【解决方案1】:

    如果你想要的只是 HTML 字符串,你可以使用通常的.innerHTML

    document.querySelector("template").innerHTML
    

    如果您想要textContent,您可以从.content.textContent 获得;像这样:

    document.querySelector("template").content.textContent
    

    如果您想实际迭代 template 子节点或对其内容执行其他任何操作,则需要使用 .content 属性,该属性返回 DocumentFragment

    从那里你有childrenfirstElementChildlastElementChildchildElementCountfind()findAll()querySelector()querySelectorAll()getElementById;至少最终——除了query* 方法和getElementById()。不确定 Safari 是否支持其中的大部分内容(约 2015-10 年)。而且我认为还没有人支持find()/findAll()

    【讨论】:

    • 我希望能够更改模板中 HTML 的内容,然后将 HTML 作为字符串返回,我可以使用 innerHTML 属性吗?
    • 当然——如果您尝试使用 document.querySelector("template").innerHTML = "<div>Some new content</div>" 设置它,然后使用 var foo = document.querySelector("template").innerHTML 获取它,我想您会发现它可以正常工作。
    猜你喜欢
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    • 2019-02-09
    • 2012-11-17
    • 2019-12-31
    • 1970-01-01
    相关资源
    最近更新 更多