我使用AJAX将数据追加到<div>元素,其中我从JavaScript填充<div>。我怎么能追加新的数据<div>而不丢失以前的数据在其中找到?
当前回答
如果你想要快速完成并且不想丢失引用和侦听器,请使用:.insertAdjacentHTML();
它不会重新解析它正在使用的元素,因此它不会破坏元素内部的现有元素。这一点,以及避免序列化的额外步骤,使其比直接innerHTML操作快得多。”
支持所有主流浏览器(IE6+, FF8+, all Others和Mobile): http://caniuse.com/#feat=insertadjacenthtml
例子来自https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>
其他回答
你可以使用jQuery。这就很简单了。
下载jQuery文件,将jQuery添加到你的HTML中 或者你可以使用在线链接:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
试试这个:
$("#divID").append(data);
即使这样也可以:
var div = document.getElementById('divID');
div.innerHTML += 'Text to append';
为什么不直接使用setAttribute ?
thisDiv.setAttribute('attrName','data you wish to append');
然后你可以通过以下方法获得这些数据:
thisDiv.attrName;
下面的方法不像其他方法那么通用,但是当您确定div的最后一个子节点已经是文本节点时,它非常有用。这样就不会使用appendData MDN Reference appendData创建新的文本节点
let mydiv = document.getElementById("divId");
let lastChild = mydiv.lastChild;
if(lastChild && lastChild.nodeType === Node.TEXT_NODE ) //test if there is at least a node and the last is a text node
lastChild.appendData("YOUR TEXT CONTENT");
如果你想要快速完成并且不想丢失引用和侦听器,请使用:.insertAdjacentHTML();
它不会重新解析它正在使用的元素,因此它不会破坏元素内部的现有元素。这一点,以及避免序列化的额外步骤,使其比直接innerHTML操作快得多。”
支持所有主流浏览器(IE6+, FF8+, all Others和Mobile): http://caniuse.com/#feat=insertadjacenthtml
例子来自https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?