我在让jquery对象呈现为html时遇到问题。
在下面的代码中,tickBoxgets呈现为,[object Object]而不是html,而其余所有都正确呈现。
我知道我可以将其添加为字符串,但这不是这里的目标。
为什么不将其tickBox呈现为html?
const legendData = ['hello world', 'welcome back', 'hotel california', 'never leave'];
const tickBox = $('<div/>', {
class: 'tickBox',
html: $('<div/>', {
class: 'ticked'
})
});
const legendContent = legendData.map(item => {
return $('<li/>', {
dataId: `${item.split(' ')[0]}`,
html: `${tickBox} ${item}`
/* I know I could do this */
//html: `<div class="tickBox"><div class="ticked"></div></div> ${item}`
});
});
$('<div/>', {
id: 'chartLegend',
class: 'legend',
title: 'Chart legend',
html: '<p id="chartLegendHeader">Legend</p>'
}).appendTo(`#chartContainer`);
$('<ul/>', {
class: 'legend',
html: legendContent
}).appendTo('#chartLegend');Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chartContainer"></div>Run Code Online (Sandbox Code Playgroud)
问题是您需要以某种方式将HTML节点序列化为字符串,以便插值正确工作。
一种方法是使用outerHTML相应的本机元素:
const legendData = ['hello world', 'welcome back', 'hotel california', 'never leave'];
const tickBox = $('<div/>', {
class: 'tickBox',
html: $('<div/>', {
class: 'ticked'
})
});
const legendContent = legendData.map(item => {
return $('<li/>', {
dataId: `${item.split(' ')[0]}`,
html: `${tickBox[0].outerHTML} ${item}`
});
});
$('<div/>', {
id: 'chartLegend',
class: 'legend',
title: 'Chart legend',
html: '<p id="chartLegendHeader">Legend</p>'
}).appendTo(`#chartContainer`);
$('<ul/>', {
class: 'legend',
html: legendContent
}).appendTo('#chartLegend');Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chartContainer"></div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
295 次 |
| 最近记录: |