如何将jquery对象呈现为html-参见[object Object] [英] How to render jquery objects to html - seeing [object Object]

查看:84
本文介绍了如何将jquery对象呈现为html-参见[object Object]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在获取jquery对象以呈现为html时遇到问题.

I'm having an issue getting jquery objects to render as html.

在下面的代码中,tickBox被呈现为[object Object]而不是html,而其余所有元素均被正确呈现.

In the code below, the tickBox gets rendered as [object Object] and not as html whereas all the rest is rendered correctly.

我知道我可以将其添加为字符串,但这不是这里的目标.

I know I could just add it as a string but that's not the goal here.

为什么tickBox不呈现为html?

Why does the tickBox not render as 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');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chartContainer"></div>

推荐答案

问题是您需要以某种方式将HTML节点序列化为字符串,以便插值正确工作.

The problem is that you somehow need to serialize the HTML node to string, so that the interpolation works correctly.

一种方法是使用相应本机元素的outerHTML:

One way is to use outerHTML of the corresponding native element:

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');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chartContainer"></div>

这篇关于如何将jquery对象呈现为html-参见[object Object]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆