[英]Javascript array to html div tag .aspx
I have an array in JS that I get from c# back end as...我在 JS 中有一个数组,它是从 c# 后端获取的,作为...
<script>
var categoryLists = <%= this.javaSerial.Serialize(this.categoryList) %>;
</script>
And my HTML is我的 HTML 是
<div id="categories">
</div>
What is the best way that I can display the contents of the JS array in the div with id as categories?我可以在 div 中以 id 作为类别显示 JS 数组内容的最佳方式是什么?
PS- I am open to both JS, and Jquery. PS-我对 JS 和 Jquery 都开放。 I also have a huge c# backend.我也有一个巨大的 c# 后端。
While essentially the same as @akerr's existing js answer, assuming that categoryList outputs as an array, here's a one-liner that will generate the same result.虽然本质上与@akerr 现有的 js 答案相同,但假设 categoryList 输出为数组,但这里有一个将生成相同结果的单行代码。
var categories = ["category 1", "category 2", "category 3"]; $("#categories").append("<ul>" + categories.map((e, i) => "<li>" + e + "</li>").join("") + "</ul>")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="categories"> </div>
Not knowing what the data looks like, I would suggest something like this.不知道数据是什么样的,我会建议这样的事情。
EDIT: Another option that may be a bit cleaner:编辑:另一个可能更清洁的选项:
JS JS
let list = document.getElementById('category-list')
categoryLists.forEach(function (category) {
let li = document.createElement('li');
list.appendChild(li);
li.innerHTML += category;
});
JS JS
let list = document.getElementById('category-list')
for (var category in categoryLists) {
list.innerHTML += '<li>' + category + '</li>';
console.log(category);
}
HTML HTML
<div id="categories">
<ul id="category-list">
</ul>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.