[英]Give an dynamically created element an id
I have created a posting system in js and for the element I create within the unordered list I want to assign it an id (eg <p id="Hello">...</p>
).我在 js 中创建了一个发布系统,对于我在无序列表中创建的元素,我想为其分配一个 id(例如<p id="Hello">...</p>
)。 Using the posting system (in js) the newly created html element shall be given an id.使用发布系统(在 js 中),新创建的 html 元素将被赋予一个 id。
js code: 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 code: 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>
This adds id='1' to the small tag and will increment by 1 each time you add an image.这会将 id='1' 添加到小标签,并且每次添加图像时都会增加 1。 Just declare a global for id and then set para.id = id只需为 id 声明一个全局,然后设置 para.id = id
var id=0; 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"); id++; para.id=id; 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); }
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.