我使用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>
其他回答
即使这样也可以:
var div = document.getElementById('divID');
div.innerHTML += 'Text to append';
试试这个:
var div = document.getElementById('divID');
div.innerHTML += 'Extra stuff';
java脚本
document.getElementById("divID").html("this text will be added to div");
jquery
$("#divID").html("this text will be added to div");
使用不带任何参数的.html()来查看您已经输入。 在代码中使用这些函数之前,可以使用浏览器控制台快速测试它们。
如果你想要快速完成并且不想丢失引用和侦听器,请使用:.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>
为什么不直接使用setAttribute ?
thisDiv.setAttribute('attrName','data you wish to append');
然后你可以通过以下方法获得这些数据:
thisDiv.attrName;
推荐文章
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有JQuery)?
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 在输入type="number"时禁用webkit的旋转按钮?
- 如何在另一个元素之后添加一个元素?
- 我如何有效地解析HTML与Java?
- “ ”和“”有什么区别?
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?