如何将 <Button> 附加到 <li> ?(javascript)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28830982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I Append a <Button> to a <li> ? (javascript)
提问by Darren Reeder
This function is run everytime an item is added to an array... It simply creates an "li" element, appends some text to that item... and then appends it to a "ul" element (#requestList)...
每次将项目添加到数组时都会运行此函数...它只是创建一个“li”元素,将一些文本附加到该项目...然后将其附加到“ul”元素(#requestList)...
function UpdateListOnScreen(NewListItem){
var grabList = document.getElementById('requestList');
var text = ""+ GetCalendarName(NewListItem.calChoice) +" For "+ GetLessonSlot(NewListItem.lessonChoice) + " On " + GetDateInTextForm(NewListItem.date) + "";
var entry = document.createElement('li');
entry.id = list.length-1;
entry.className = "ItemNotChecked";
entry.appendChild(document.createTextNode(text));
grabList.appendChild(entry);
}
Something im struggling to figure out is how do I add a "button" tag onto that List item? I want every List item to have its own "button" tag, but cant seem to figure out how I append a button to the li after appending the text to the li..
我正在努力弄清楚的是如何在该列表项上添加“按钮”标签?我希望每个列表项都有自己的“按钮”标签,但似乎无法弄清楚在将文本附加到 li 后如何将按钮附加到 li ..
Hope that makes sense :S
希望这是有道理的:S
Thanks :D
感谢:D
回答by Tushar
This is an example how you can insert button :
这是一个如何插入按钮的示例:
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Four"));
var button = document.createElement("button");
button.innerHTML = "asdasd";
li.appendChild(button);
li.setAttribute("id","element4");
ul.appendChild(li);
alert(li.id);
<ul id="list"></ul>
回答by HaukurHaf
This should do the trick;
这应该可以解决问题;
function UpdateListOnScreen(NewListItem){
var grabList = document.getElementById('requestList');
var text = ""+ GetCalendarName(NewListItem.calChoice) +" For "+ GetLessonSlot(NewListItem.lessonChoice) + " On " + GetDateInTextForm(NewListItem.date) + ""; var entry = document.createElement('li'); entry.id = list.length-1; entry.className = "ItemNotChecked"; entry.appendChild(document.createTextNode(text));
/*Add a button to each LI */
var button = document.createElement('button');
button.innerText = 'Click me!';
entry.appendChild(button);
grabList.appendChild(entry); }