使用javascript注入html的最佳方法 [英] best way to inject html using javascript

查看:82
本文介绍了使用javascript注入html的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这不是太主观。我觉得有一个明确的答案,所以这里有。

I'm hoping that this isn't too subjective. I feel there is a definitive answer so here goes.

我想使用JS(无库)动态创建这个html:

I want to create this html on the fly using JS (no libraries):

<a href="#" id="playButton">Play</a>
<a href="javascript: void(0)" id="muteUnmute">Mute</a>
<div id="progressBarOuter"> 
  <div id="bytesLoaded"></div>
    <div id="progressBar"></div>
</div>
<div id="currentTime">0:00</div>
<div id="totalTime">0:00</div>

使用javascript。我知道我可以使用createElement等来做到这一点但是对于每个元素来说,这似乎是非常冗长的。任何人都可以建议一种更简洁的方法。

using javascript. I know I can do this using createElement etc but it seems extremely long winded to do this for each element. Can anyone suggest a way to do this with more brevity.

我无法访问此项目中的库....所以没有jquery等。

I do not have access to a library in this project....so no jquery etc.

推荐答案

将整个事物推入JS变量:

Shove the entire thing into a JS variable:

var html = '<a href="#" id="playButton">Play</a>';
html += '<a href="javascript: void(0)" id="muteUnmute">Mute</a>';
html += '<div id="progressBarOuter"><div id="bytesLoaded"></div><div id="progressBar"></div></div>';
html += '<div id="currentTime">0:00</div>';
html += '<div id="totalTime">0:00</div>';

然后:

document.getElementById("parentElement").innerHTML = html;

如果你想要N:

document.getElementById("totalTime").innerHTML = "5:00";

这篇关于使用javascript注入html的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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