我已经在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>
最佳答案
这会将id ='1'添加到小标签,并且每次添加图片时都会增加1。只需为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>
关于javascript - 给动态创建的元素一个id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60662728/