[英]create dynamically ul & li
Consider the following code 考虑以下代码
<div class = 'text-danger'><ul id = 'validation_summary'></ul></div>
How can I add values(li) dynamically to ul? 如何动态地向ul添加值(li)? My incomplete code is as follows: 我不完整的代码如下:
Object.entries(response.errors).forEach(([key,value]) => {
$("validation_summary").innerHTML = ('<li>' + key + ' value +' </li>').appendTo($("div:has(ul)"));
});
Try this example based on your code: 根据您的代码尝试以下示例:
const response = { errors: { err1: 'error 1', err2: 'error 2', err3: 'error 3', } } Object.entries(response.errors).forEach(([key,value]) => { $("#validation_summary").innerHTML = $("div:has(ul)").append('<li>' + key + ': ' + value +' </li>'); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='text-danger'> <ul id='validation_summary'></ul> </div>
Instead of looping and continuously adding items to the DOM (which is a relatively expensive operation), I suggest you instead build a string of li
from your response.errors
object, which you can then add to #validation_summary
. 我建议您不循环并向DOM连续添加项目(这是一个相对昂贵的操作),而建议您从response.errors
对象构建一个li
字符串,然后将其添加到#validation_summary
。 To build the string, I have used .reduce()
. 为了构建字符串,我使用了.reduce()
。 I have also used the .html()
(instead of .innerHTML
) method to then add the list of items to #validation_summary
. 我还使用了.html()
(而不是.innerHTML
)方法,然后将项目列表添加到#validation_summary
。
See example below: 请参见下面的示例:
const response = { errors: { "key1": "val1", "key2": "val2", "key3": "val3", } } const list_items = Object.entries(response.errors) .reduce((acc, [key, value]) => acc + '<li>' + key + ' ' + value + '</ li>', ''); $("#validation_summary").html(list_items)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='text-danger'> <ul id='validation_summary'></ul> </div>
<div class = 'text-danger'><ul id = 'validation_summary'></ul></div>
let errors = {one:"test 1",two : "test 2"}; Object.entries(errors).forEach(([key,value]) => { $(`<li>${key} -- ${value} </li>`).appendTo("ul#validation_summary"); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class = 'text-danger'><ul id='validation_summary'></ul></div>
You can just append to your ul while looping through it. 您可以在遍历ul时附加到ul上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.