如何从以下代码获取li id?
我的项目需要它,我已经研究并尝试过,但仅显示为“空”
window.saveAndDisplay = function() {
var list = document.getElementById('dropBox').children;
var result = "Names are: <br />";
for (var i = 0; i < list.length; i++) {
result += document.getElementById(list[i]) + "<br />";
}
document.getElementById('demo').innerHTML = result;
}
答案 0 :(得分:1)
要获取元素的ID,您可以访问对象的id
属性。
以您的示例为例:
window.saveAndDisplay = function() {
var list = document.getElementById('dropBox').children;
var result = "Names are: <br />";
for (var i = 0; i < list.length; i++) {
result += list[i].id + "<br />";
}
document.getElementById('demo').innerHTML = result;
}
但是,由于似乎您想要的是Names而不是object-id,因此可以选择通过访问textContent
-property这样的方式来获取元素的文本内容:
window.saveAndDisplay = function() {
var list = document.getElementById('dropBox').children;
var result = "Names are: <br />";
for (var i = 0; i < list.length; i++) {
result += list[i].textContent + "<br />";
}
document.getElementById('demo').innerHTML = result;
}
答案 1 :(得分:0)
我还更改了br的位置,以获取更清晰的代码。
window.dragStart = function(e) {
e.dataTransfer.effectAllowed = "move";
e.dataTransfer.setData("Text", e.target.getAttribute("id"));
}
window.dragOver = function(e) {
e.preventDefault();
e.stopPropagation();
}
window.drop = function(e) {
e.stopPropagation();
e.preventDefault();
var data = e.dataTransfer.getData("Text");
e.target.appendChild(document.getElementById(data));
//when i dropped an element and if i made mistake, by clicking on element i remove it from dropbox
var txt1 = document.getElementById(data);
txt1.onclick = function () {
document.getElementById(data).remove();
this.remove();};
}
window.saveAndDisplay = function() {
var list = document.getElementById('dropBox').children;
var result = "Names are: <br></br>";
for (var i = 0; i < list.length; i++) {
result += list[i].textContent;
result += "<br><br/>";
}
document.getElementById('demo').innerHTML = result;
}
#dropBox {
width: 150px;
height: 200px;
border: 1px solid gray;
background: lightyellow;
text-align: left;
margin: 20px 0;
color: orange;
}
<body>
<h2>Drag & Drop Demo</h2>
<p>Drag and drop the image into the drop box:</p>
<div id="dropBox" ondragover="dragOver(event);" ondrop="drop(event);" >
</div>
<!--for some reason when i drop element in dropbox, it doesn't go in new line, so i wrote this <br>. If you have better solution, please tell me.-->
<ul>
<li id="dragA" draggable="true" ondragstart="dragStart(event);">Marko
Maric</li>
</ul>
<input type='button' onclick='saveAndDisplay()' value='Submit'/>
<!--by clicking on submit button, I want the names i picked to display in this paragraph-->
<p id="demo">Names are:</p>
</body>
</html>