简体   繁体   English

.appendChild()单击HTML元素

[英].appendChild() an HTML element on click

I wanted to copy an entire row including its' siblings and contents on button click. 我想复制整个行,包括其兄弟姐妹和单击按钮时的内容。 When I click the button the element, it appears in the console but doesn't append to the page. 当我单击按钮时,该元素会出现在控制台中,但不会追加到页面上。 This is my code: 这是我的代码:

It doesn't show any error messages. 它不显示任何错误消息。 I've tried innerHTML/outerHTML or append() it doesn't work. 我试过innerHTML / outerHTML或append()无效。

$(document).ready(function() {

    $('#addSubFBtn').on('click', function() {
        var itm = document.getElementById("trFb");
        var wrapper = document.createElement('div');
        var el = wrapper.appendChild(itm);
        document.getElementById("tbFb").append(el);
        console.log(el);
    });
});

Seems like what you're trying to do is clone the item after you get it from your document. 似乎您要尝试的是从文档中获取项目后对其进行克隆。 W3schools website explains how to accomplish this. W3schools网站介绍了如何实现此目的。 Check out the link: https://www.w3schools.com/jsref/met_node_clonenode.asp 查看链接: https : //www.w3schools.com/jsref/met_node_clonenode.asp

Once you clone the node, [appendchild] should work as intended 克隆节点后,[appendchild]应该可以正常工作

Not sure (as said without seeing related HTML) but i see flaw in your logic: 不确定(如未看到相关HTML所述),但我发现您的逻辑存在缺陷:

var itm = document.getElementById("trFb"); still exist on the document(so in the page) so you've to retrieve it before you want to add/move it to another place. 仍然存在于文档中(因此在页面中),因此您必须先检索它,然后才能将其添加/移动到另一个位置。 using .removeElement will return you removed element(or null if no element matche the selector) so correct script should be: 使用.removeElement将返回删除的元素(如果没有元素与选择器匹配,则返回null),因此正确的脚本应为:

var itm=document.getElementById("trFb").parentNode.removeChild(document.getElementById("trFb")); as shown here to remove element you've to use method on to parent element. 如此处所示,要删除元素,您必须对父元素使用method。 So you can add it to any other element existing. 因此,您可以将其添加到现有的任何其他元素中。 For more specific use or element created in global JS variable (such an createElement not yet appended) you can see : document.createDocumentFragment(); 有关在全局JS变量中创建的更特定的用法或元素(例如尚未添加的createElement),请参见: document.createDocumentFragment(); as explained here https://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment 如此处所述https://developer.mozilla.org/zh-CN/docs/Web/API/Document/createDocumentFragment

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM