gpt4 book ai didi

javascript - 使用数据源中的数据将 "literal HTML"添加到 HTML 小部件?

转载 作者:行者123 更新时间:2023-11-28 11:02:42 24 4
gpt4 key购买 nike

在 FreeBoard 中创建 HTML 小部件时,会显示以下文本:

Can be literal HTML, or javascript that outputs HTML.

我知道我可以执行以下操作来返回带有数据的 HTML,但如果我想做一些更复杂的事情,我更喜欢使用文字 HTML

返回带数据的 html

return "<div style='color: red'>This is a red timestamp: " + datasources["DS"]["Timestamp"] + "</div>"

没有数据的文本 html

<div style='color: red'>
This is red text.
</div>
<div style='color: blue'>
This is blue text.
</div>

这两个都有效。我的问题是,如何将数据从数据源插入到文本 html 示例中?

有关更多上下文,请参阅编辑器顶部的内容:

This javascript will be re-evaluated any time a datasource referenced here is updated, and the value you return will be displayed in the widget. You can assume this javascript is wrapped in a function of the form function(datasources) where datasources is a collection of javascript objects (keyed by their name) corresponding to the most current data in a datasource.

这是默认文本:

// Example: Convert temp from C to F and truncate to 2 decimal places.
// return (datasources["MyDatasource"].sensor.tempInF * 1.8 + 32).toFixed(2);

最佳答案

我不知道自由板框架,但通用解决方案是使用 HTML5 模板(如果您的浏览器支持要求允许的话)。

function supportsTemplate() {
return 'content' in document.createElement('template');
}

if (supportsTemplate()) {
alert('browser supports templates');
} else {
alert('browser does not support templates');
}

var template = document.querySelector('#timestamp-template');

var timestamp = template.content.querySelector('.timestamp');
timestamp.innerHTML = new Date().toLocaleString();

var clone = document.importNode(template.content, true);

var output = document.querySelector('#output');
output.appendChild(clone);
<template id="timestamp-template">
<div style='color: red' class="timestamp">
This is default red text.
</div>
<div style='color: blue'>
This is blue text.
</div>
</template>


<div id="output"></div>

您显然需要调整此策略以支持任何数据源并转变您的项目需求。

对 HTML5 的支持失败 template元素,您也可以使用 <script type="text/template"> .

关于javascript - 使用数据源中的数据将 "literal HTML"添加到 HTML 小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31592886/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com