如何使用JavaScript创建此HTML代码块

时间:2018-05-23 18:32:46

标签: javascript

我想使用JavaScript创建这个HTML代码块,我该怎么办?    此?

<a>
<span class="image"><img src="<%=request.getContextPath() 
%>/resources/build/images/cogs.jpg" alt="Profile Image" width="100"> 
</span>
<span>
<span id="timeDiv2"></span>
<span class="time" id="timeDiv3"></span>
</span>
<span class="message" id="timeDiv4">
</span>
</a>

2 个答案:

答案 0 :(得分:2)

我是这样写的。无需弄乱您的代码。看看这里。

var aelem = createNewElement({elem:"a"});

var span =  createNewElement({elem:"span",class:"image"});
var img =  createNewElement({elem:"img",src:"https://comps.canstockphoto.co.uk/smily-picture_csp18918415.jpg"});
span.append(img);

var span1 = createNewElement({elem:"span"});
var TimeDiv2 = createNewElement({elem:"span",id:"timeDiv2"}),
timeDiv3 = createNewElement({elem:"span",id:"timeDiv3",class:"time"});
 
span1.append(TimeDiv2);
span1.append(timeDiv3);
timeDiv4 = createNewElement({elem:"span",id:"timeDiv4",class:"message"});
aelem.append(span);
aelem.append(span1);
aelem.append(timeDiv4);
console.log(aelem.outerHTML);
document.getElementById('appendHere').innerHTML = aelem.outerHTML;
function createNewElement(attr){ 
      var newElem = document.createElement(attr.elem);
      if(attr.id) newElem.setAttribute("id",attr.id);
      if(attr.class) newElem.setAttribute("class",attr.class);
      if(attr.src) newElem.setAttribute("src",attr.src);  
      if(attr.href) newElem.setAttribute("href",attr.href);
       
    //Write more attribute if you want more
      return newElem;
}
<div id="appendHere"></div>

希望它会有所帮助。 谢谢

答案 1 :(得分:-2)

document.write( '<a>\n' );
document.write( '<span class=\"image\"><img src=\"<%=request.getContextPath() \n' );
document.write( '%>/resources/build/images/cogs.jpg\" alt=\"Profile Image\" width=\"100\"> \n' );
document.write( '</span>\n' );
document.write( '<span>\n' );
document.write( '<span id=\"timeDiv2\"></span>\n' );
document.write( '<span class=\"time\" id=\"timeDiv3\"></span>\n' );
document.write( '</span>\n' );
document.write( '<span class=\"message\" id=\"timeDiv4\">\n' );
document.write( '</span>\n' );
document.write( '</a>' );