我试图将这段html代码转换为javascript,以便我可以动态地将它添加到html代码中的<div>
。将html代码转换为javascript用于动态输入
The html code is
<img src="images/bg_fav.png" alt="" width="199" height="199" class="circle"/>
<a href="#" class="icon"></a>
<h2>Filename</h2>
<ul>
<li><a href="#">Add</a></li>
</ul>
我需要将此代码转换为javascript。我试图做这样的,但它似乎并没有工作:
div1 = document.getElementById('div1');
a = document.createElement('img');
a.setAttribute('src','images/bg_shop.png');
a.setAttribute('alt','');
a.setAttribute('width','199');
a.setAttribute('height','199');
a.setAttribute('className','circle');
b=document.createElement('a');
b.setAttribute('className','icon');
c=document.createElement('h2');
c.value="filename";
c.name="filename";
c.id ="filename";
d=document.createElement('ul');
d.innerHTML="<li><a href='#'>add</a></li>"
div1.appendChild(a);
div1.appendChild(b);
div1.appendChild(c);
div1.appendChild(d);
为什么它不起作用?有没有JavaScript错误?生成的html有什么问题吗?请给我们更多的信息来帮助 – 2012-02-10 16:43:47
不是一个答案,但需要考虑的是可以使用JS模板引擎:http://stackoverflow.com/questions/7788611/what-javascript-template-engines-you-recommend 。在构建HTML时,比手动将DOM节点或文本串起来要少得多。干杯。 – artlung 2012-02-10 16:46:31
您没有div1 ID的元素。坚持一个在那里,它工作正常。否则,你会得到一个“Can not call method”appendChild'null“错误。 – j08691 2012-02-10 16:47:34