如何在javascript而不是jquery中添加动态列表
How to add dynamic lists in javascript not jquery
Am的数据为
var response = '[{"id":1,"name":"Web Demo"},{"id":2,"name":"Audio Countdown"},{"id":3,"name":"The Tab Key"},{"id":4,"name":"Music Sleep Timer"}]';
var obj = JSON.parse(response);
因此,我如何动态添加列表项,以便将来如果后端的列表项增加,则应直接添加它们,以及如何链接动态和静态元素。
感谢
使用js appendChild
在html中附加每个项目,如下所示。。。
var response = [{"id":1,"name":"Web Demo"},{"id":2,"name":"Audio Countdown"},{"id":3,"name":"The Tab Key"},{"id":4,"name":"Music Sleep Timer"}] ;
for (i = 0; i < response.length; i++)
{
var node = document.createElement("LI"); // Create a <li> node
var textnode = document.createTextNode(response[i].name); // Create a text node
node.appendChild(textnode);
document.getElementById("items").appendChild(node); ///append Item
}
<div id="items"></div>
如果您想根据后端的更改来更改列表,您应该定期通过ajax进行测试。您可以使用setInterval
和CCD_ 3。
当新数据到达时,您应该删除现有列表并添加新元素来动态表示到达的数据。
setInterval(function(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
populateList(xhttp.responseText); //This is your function to create the list
}
};
xhttp.open("GET", "http://www.mybackend.com/list", true);
xhttp.send();
})
您可以使用document.createElement
函数创建一系列元素来表示您的数据。
function populateList(data) {
var obj = var obj = JSON.parse(response);
document.getElementById('myUl').remove(); //Delete the existing list
var myUi = document.createElement('ul'); //Add new list
obj.forEach(item) {
var listItem = document.createElement('li');
myUi.appendChild(li);
//Then add li details here
}
}
这只是粗略的代码。你能用Jquery比这更短的时间完成这件事吗。您甚至可以使用像Angular这样的JS框架来自动化这些任务。
如果将动态数据存储为静态数据,请使用concat
response.concat(dynamicdata);
相关文章:
- JQuery添加元素需要在我的js之前再次添加JQuery脚本
- 通过jQuery添加ng样式属性,angular不更新
- 使用HTML5 localStorage和jQuery添加到收藏夹/书签
- jQuery添加的文本不显示
- 使用Jquery添加内容
- 如何使用jQuery添加另一个对象的高度作为边距
- JavaScript/jQuery-添加添加和删除类与下一个函数之间的延迟
- 对于每个json结果,使用类jquery添加css
- Jquery添加一个类之后,如何应用css
- 使用jQuery添加和删除属性
- Jquery添加输入字段和日期选择器
- jQuery - 添加删除类 - 设置输入值
- 为什么在这种情况下要向JQuery添加两个链接
- 为图像滑块jquery添加项目符号功能
- 使用jquery添加到表单内部表中的元素不会过帐
- 如何使用jquery添加元素
- 使用Jquery添加XML元素
- 当使用javascript/jquery添加值时,html文本输入表显示不正确
- 将jquery添加到firefox扩展中
- 运行 AJAX 需要什么 - 将 jQuery 添加到页面处理 AJAX 调用