我是一个完整的JavaScript初学者,我正在尝试创建一个脚本,当一个"文件输入"页面元素获取文件加载。该脚本应该基本上创建一个p
元素,在其中插入img
,innerText
和span
,因此将所有这些都附加到表单中。除了img
:
function visualUploadFile() {
var obj = document.getElementById("hidden_file").files[0].name;
//create p object to append to the form
var pobj = document.createElement("p");
pobj.className = "form_line_file";
//nest icon inside the object
var imgico = document.createElement("img");
imgico.src = "load-ico.png";
//append img to the p - THE OBJECT IS NOT APPENDED
pobj.appendChild(imgico);
//nest file name as inner Text to the p
pobj.innerText = obj;
//create span object to write "rimuovi"
var spanobj = document.createElement("span");
spanobj.className = "rimuovi_file";
spanobj.innerHTML = "rimuovi";
//append span to the p
pobj.appendChild(spanobj);
//get form and append p child
var bigForm = document.getElementById("offerta_form");
bigForm.appendChild(pobj);
}
以下是脚本执行后的HTML,因为您只能看到img丢失:
<p class="form_line_file"> <!--p object correctly appended to the form-->
Immagine.png <!--inner Text properly appended-->
<span class="rimuovi_file"> <!--span object correctly appended-->
rimuovi
</span>
</p>
可能是一个愚蠢的错误,但我无法解决它。任何人都可以告诉我,我做错了什么不能得到附加的img作为跨度?
答案 0 :(得分:4)
添加文件名标签的方式不正确。设置innerText
会覆盖图像。而不是
pobj.innerText = obj;
试试这个:
pobj.appendChild(document.createTextNode(obj));