无法将img标签追加到p标签 [英] Not able to append an img tag to a p tag

查看:149
本文介绍了无法将img标签追加到p标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript的完全初学者,我正尝试创建一个脚本,当页面的文件输入元素获取文件时,会触发该脚本。该脚本应该基本上创建一个 p 元素,在其中插入一个 img ,一个 innerText span ,因此将所有这些附加到表单中。除了 img

I'm a complete beginner in JavaScript and I am trying to create a script which is fired when a "file input" element of the page gets a file loaded. The script should basically create a p element, insert in it an img, a innerText and a span, hence append all this into a form. Everything works fine with the script below, except for the 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缺失:

Here is the HTML after the script has been executed, as you can see only the img is missing:

<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作为跨度?

Probably is a stupid mistake, but I'm not being able to sort it out. Could anyone please tell me what I'm doing wrong not to be able to get the img appended as for the span?

推荐答案

您添加文件名称标签的方式不正确。设置 innerText 会覆盖图像。而不是

The way you are adding file name label is incorrect. Setting innerText overwrites image. Instead of

pobj.innerText = obj;

试试这个:

try this:

pobj.appendChild(document.createTextNode(obj));

这篇关于无法将img标签追加到p标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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