为动态创建的元素指定一个 id

我已经在js中创建了一个发布系统,对于我在无序列表中创建的元素,我想为其分配一个id(例如<p id="Hello">...</p>)。使用发布系统(在 js 中),新创建的 html 元素应被赋予一个 id。


js代码:


function publish() {

    var title = document.getElementById("title").value;

    var description = document.getElementById("description").value;

    var para = document.createElement("h3");

    var node = document.createTextNode(title);

    para.appendChild(node);


    var element = document.getElementById("posts");

    element.appendChild(para);


    var para = document.createElement("small");

    var node = document.createTextNode("--".concat(description, "--"));

    para.appendChild(node);


    var image = document.getElementById("posts");

    element.appendChild(para)

    var image = document.createElement("img");

    var imageInput = document.getElementById('image-file');

    image.src = URL.createObjectURL(imageInput.files[0]);

    image.style.height = '100px';

    image.style.width = '100px';


    para.appendChild(image);

}

html代码:


    <button id="publish-button" onclick="publish();">Publish</button>

        <p>Title</p>

        <input class="Title" id="title"></input>


        <p>Description</p>

        <input class="Description" id="description"></input>


        <p>Images</p>

        <input id="image-file" type="file" />

<ul id="posts">

    </ul>


HUWWW
浏览 55回答 1
1回答

一只名叫tom的猫

这会将 id='1' 添加到小标签,并且每次添加图像时都会增加 1。只需为 id 声明一个全局,然后设置 para.id = idvar id=0;function publish() {&nbsp; &nbsp; var title = document.getElementById("title").value;&nbsp; &nbsp; var description = document.getElementById("description").value;&nbsp; &nbsp; var para = document.createElement("h3");&nbsp; &nbsp; var node = document.createTextNode(title);&nbsp; &nbsp; para.appendChild(node);&nbsp; &nbsp; var element = document.getElementById("posts");&nbsp; &nbsp; element.appendChild(para);&nbsp; &nbsp; var para = document.createElement("small");&nbsp; &nbsp; id++;&nbsp; &nbsp; para.id=id;&nbsp; &nbsp; var node = document.createTextNode("--".concat(description, "--"));&nbsp; &nbsp; para.appendChild(node);&nbsp; &nbsp; var image = document.getElementById("posts");&nbsp; &nbsp; element.appendChild(para)&nbsp; &nbsp; var image = document.createElement("img");&nbsp; &nbsp; var imageInput = document.getElementById('image-file');&nbsp; &nbsp; image.src = URL.createObjectURL(imageInput.files[0]);&nbsp; &nbsp; image.style.height = '100px';&nbsp; &nbsp; image.style.width = '100px';&nbsp; &nbsp; para.appendChild(image);}<button id="publish-button" onclick="publish();">Publish</button>&nbsp; &nbsp; &nbsp; &nbsp; <p>Title</p>&nbsp; &nbsp; &nbsp; &nbsp; <input class="Title" id="title"></input>&nbsp; &nbsp; &nbsp; &nbsp; <p>Description</p>&nbsp; &nbsp; &nbsp; &nbsp; <input class="Description" id="description"></input>&nbsp; &nbsp; &nbsp; &nbsp; <p>Images</p>&nbsp; &nbsp; &nbsp; &nbsp; <input id="image-file" type="file" /><ul id="posts">&nbsp; &nbsp; </ul>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5