没有jQuery的.html()和.append()

yee*_*ha1 31 html javascript jquery

谁能告诉我如何在不使用jQuery的情况下使用这两个函数?

我正在使用一个我不能使用jQuery的预编码应用程序,我需要从一个div获取HTML,并使用JS将其移动到另一个div.

Alb*_*reo 52

你可以替换

var content = $("#id").html();
Run Code Online (Sandbox Code Playgroud)

var content = document.getElementById("id").innerHTML;
Run Code Online (Sandbox Code Playgroud)

$("#id").append(element);
Run Code Online (Sandbox Code Playgroud)

document.getElementById("id").appendChild(element);
Run Code Online (Sandbox Code Playgroud)


ori*_*dam 19

  • .html(new_html) 可以替换为 .innerHTML=new_html
  • .html() 可以替换为 .innerHTML
  • .append() 方法有3种模式:
    • 附加一个jQuery元素,这与此无关.
    • 追加/移动dom元素.
      .append(elem)可以替换为.appendChild(elem)
    • 附加HTML代码.
      .append(new_html)可以替换为.innerHTML+=new_html

例子

var new_html = '<span class="caps">Moshi</span>';
var new_elem = document.createElement('div');
// .html(new_html)
new_elem.innerHTML = new_html;
// .append(html)
new_elem.innerHTML += ' ' + new_html;
// .append(element)
document.querySelector('body').appendChild(new_elem);
Run Code Online (Sandbox Code Playgroud)

笔记

  1. 您无法使用innerHTML附加标记.你必须使用appendChild.

  2. 如果您的页面是严格的xhtml,附加非严格的xhtml将触发脚本错误,这将破坏代码.在这种情况下,你会想要包装它try.

  3. jQuery提供了其他一些不太简单的快捷方式,例如prependTo/appendTo after/before 更多.

  4. 一个人不能<script>使用附加标签innerHTML.你必须使用appendChild


Mik*_*uel 10

要将HTML从一个div复制到另一个div,只需使用DOM即可.

function copyHtml(source, destination) {
  var clone = source.ownerDocument === destination.ownerDocument
      ? source.cloneNode(true)
      : destination.ownerDocument.importNode(source, true);
  while (clone.firstChild) {
    destination.appendChild(clone.firstChild);
  }
}
Run Code Online (Sandbox Code Playgroud)

对于大多数应用程序来说,inSameDocument总是如此,所以当错误时,你可能会忽略所有功能部件.如果您的应用在同一个域中有多个框架通过JavaScript进行交互,您可能希望将其保留在其中.

如果要替换HTML,可以通过清空目标然后复制到目标来实现:

function replaceHtml(source, destination) {
  while (destination.firstChild) {
    destination.removeChild(destination.firstChild);
  }
  copyHtml(source, destination);
}
Run Code Online (Sandbox Code Playgroud)

  • 你知道你可以"克隆(真实)"源节点吗?:-) (2认同)