[英]How do I add an HTML element into a div using jQuery while passing variables as content?
Say I have a list like so: 说我有一个像这样的清单:
<ul id="my-list">
<li class="list-item" data-role="collapsible">List Item</li>
<li class="list-item" data-role="collapsible">List Item</li>
<li class="list-item" data-role="collapsible">List Item</li>
</ul>
I want to be able to add another li
element with the class list-item
and maybe the data-role collapsible
at the end of the list. 我希望能够添加其它
li
与类元素list-item
,也许这个数据角色collapsible
,在列表的末尾。 But, I want to pass the contents of a variable to the inside of the new li
tag. 但是,我想将变量的内容传递到新的
li
标签的内部。 Say the variable is var myVariable = "Contents of Variable";
说变量是
var myVariable = "Contents of Variable";
Is there a way to do this using jQuery and/or JavaScript? 有没有办法使用jQuery和/或JavaScript?
You could clone one of the existing tags: 您可以克隆现有标签之一:
$('#my-list li').first().clone().text(myVariable).appendTo('#my-list');
And with plain JavaScript: 并使用普通的JavaScript:
var list = document.getElementById('my-list');
var elem = list.firstChild.cloneNode();
elem.textContent = myVariable;
list.appendChild(elem);
Try this: 尝试这个:
var myVariable = "Contents of Variable";
$("#my-list").append("<li class='list-item' data-role='collapsible'>" + myVariable + "</li>");
您可以使用
$('#my-list').append('<li class="list-item" data-role="collapsible">' + myVariable + '</li>');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.