我正在使用JavaScript和HTML,我希望能够将用户输入添加到HTML的多级列表中。我首先以HTML编写了一个多级列表。作为示例,我列出了有关狗的信息。
<div>
<h3> Dogs </h3>
<ul id="myList">
<li><b>Dog Breeds</b>
<ul>
<li class="facts"> There are a approximately 340 recognized breeds.</li>
</ul>
</li>
<li><b>Dog Fur</b>
<ul>
<li class="facts"> Depending on the dogs, there are a lot of different kinds of fur.</li>
</ul>
</li>
</ul>
</div>
在此列表下面,我创建了两个可以保存用户输入的字段,并在其旁边的按钮可以将输入的信息添加到列表中。我的按钮和类型字段的代码如下:
<input type='text' id='input' placeholder="Title"/>
<button type="button" id="add">Add new dog fact</button><br>
<textarea id="input2" rows="5" cols="18" placeholder="The dog fact.."></textarea>
为了将输入添加到列表中,我编写了这段代码:“ myList”是我给出的无序列表的ID。
document.getElementById("add").onclick = function() {
var title = document.getElementById("input").value;
var description = document.getElementById("input2").value;
var li = document.createElement("li");
li.textContent = title + description;
document.getElementById("myList").appendChild(li);
document.getElementById("input2").value = ""; // clears the value
document.getElementById("input").value = ""; // clears the value
我现在的问题是,它的结构不会像我想要的那样。通过使用上面的代码,如果我输入“ Dog Size”作为“ Dog Size”作为标题并且“ Dogs can big and small”,则输出将如下所示。作为描述:
狗的大小狗可以大也可以小。
而不是:
狗的大小狗可以是大小的。
没有人知道如何更改此设置,因此用户输入的结构将与列表其余部分的结构相同?这样描述将嵌套在标题中?我知道这是因为我已经将“ li.textContent”定义为“ title + description”,我只是不知道如何添加描述数据。我试图在javaScript代码中创建2个新的列表元素,但是,正如预期的那样,这创建了2个新的列表元素,然后我尝试使用“ title.style.listStyleType =” none“;”,来为描述元素设置样式。但是如果我将其放在函数中,则整个函数将停止工作。我很困惑,如果有人能够帮助我,我将非常感激!谢谢:)
使用innerHTML
并在<br>
和title
之间添加description
。
document.getElementById("add").onclick = function() {
var title = document.getElementById("input").value;
var description = document.getElementById("input2").value;
var li = document.createElement("li");
li.innerHTML = title + "<br>" + description;
document.getElementById("myList").appendChild(li);
document.getElementById("input2").value = "";
document.getElementById("input").value = "";
}
<div>
<h3> Dogs </h3>
<ul id="myList">
<li><b>Dog Breeds</b>
<ul>
<li class="facts"> There are a approximately 340 recognized breeds.</li>
</ul>
</li>
<li><b>Dog Fur</b>
<ul>
<li class="facts"> Depending on the dogs, there are a lot of different kinds of fur.</li>
</ul>
</li>
</ul>
</div>
<input type='text' id='input' placeholder="Title" />
<button type="button" id="add">Add new dog fact</button><br>
<textarea id="input2" rows="5" cols="18" placeholder="The dog fact.."></textarea>
</div>