Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
6.1k views
in Technique[技术] by (71.8m points)

使用javascript将元素插入html

我想问问有没有办法用javascript插入html内容,就像我有一张桌子,里面有一个tbody,里面有我要使用javascript插入元素的地方,就像我要插入tr一样,在tr里面要插入5 td,我希望那5 td具有不同的内容,如果您尝试将上述所有内容放入代码中,它将看起来像这样

for(let i = 1; i< 38; i++){
        
        let swd = {
            active: data.statewise[i].active,
            confirmed: data.statewise[i].confirmed,
            deaths: data.statewise[i].deaths,
            recovered: data.statewise[i].recovered
        }

        let swdb = document.getElementById('swdb');

        let swtr = document.createElement('tr');

        swdb.appendChild(swtr);

        for(let j = 1; j<6; j++){
            let swtd = document.createElement('td');
            swtr.appendChild(swtd);
        }
    }

对我来说,挑战是在同一tr的td中插入不同的内容。在那之后的最终html代码应该看起来像这样:-

                    <tr>
                        <td>Custom content 1</td>
                        <td id="active"> Custom content 2</td>
                        <td id="conf">Custom content 3</td>
                        <td id="deaths">Custom content 4</td>
                        <td id="recov">Custom content 5</td>
                    </tr>

之后,我将生成更多这样的tr。

希望您理解我的问题并为我提供帮助!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

2 Answers

0 votes
by (71.8m points)

您只需要innerText在td中添加内容:

您可以像这样制作一个对象数组:

const customContent = [
    {id:"",content:"Custom content 1"},
    {id:"active",content:data.statewise[i].active},
    {id:"confirmed",content:data.statewise[i].confirmed},
    {id:"deaths",content:data.statewise[i].deaths},
    {id:"recov",content:data.statewise[i].recovered},
]

并像这样使用它们:

customContent.forEach(item => {
  let swtd = document.createElement('td');
  swtd.id = item.id;
  swtd.innerText = item.content;
  swtr.appendChild(swtd);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
0 votes
by (71.8m points)

实际上与@ b3hr4d相同的示例,但您不应.innerHTML在纯文本上使用,请在.textContent之间选择.innerText祝你好运=)

const contentList = [
  { id: "", text: 'Custom content 1' },
  { id: 'active', text: 'Custom content 2' },
];

const tr = document.createElement('tr');
contentList.forEach(({ id, text }) => {
  const td = document.createElement('td');
  if (id) td.setAttribute('id', id);
  td.textContent = text;
  tr.appendChild(td);
});

const root = document.querySelector('#root');
root.appendChild(tr);

结果

<div id="root">
  <tr>
    <td>Custom content 1</td>
    <td id="active">Custom content 2</td>
  </tr>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...