简体   繁体   English

追加到不在DOM树中的元素

[英]append to element not in DOM tree

So I am building a div: 所以我正在建立一个div:

 var editArea =  '<div class="edit-container" style="padding-bottom: 10px;">' +
                '       <textarea class="form-control" style="margin-bottom:5px;">'+
                '       </textarea>' +
                '       <button type="button" class="btn right "><i class="fa fa-times-circle "></i>Leave Editor</button>'+
                '       <button type="button" class="btn submit-edit pull-right right " style="color:#fff;padding-top:5px; background-color: #3D8A11; border: 1px solid #f2f2f2;"><i class="fa fa-check-circle"></i>Submit</button>'+
                '</div>';

and want to append something to it before inserting it in the DOM: 并希望在将其插入DOM之前对其进行附加:

for(i = 0; i < data.length; i++){
var fileLink = '<a href="#">' +data[i].username+'</a>';
editArea.('.edit-container').prepend(fileLink);
}

How would I go about doing this given my somewhat unconventional syntax for building the div? 考虑到我用于构建div的某种非常规语法,我将如何去做? I am potentially open to building the initial div differently, if you suggest so. 如果您建议的话,我可能愿意以不同的方式建立初始div。 I just like that style for its one-line approach. 我喜欢这种风格的单行方法。

WHAT WORKED: 工作原理:

var editArea =  $('<div class="edit-container" style="padding-bottom: 10px;">' +
                    '       <textarea class="form-control" style="margin-bottom:5px;">'+
                    '       </textarea>' +
                    '       <button type="button" class="btn right "><i class="fa fa-times-circle "></i>Leave Editor</button>'+
                    '       <button type="button" class="btn submit-edit pull-right right " style="color:#fff;padding-top:5px; background-color: #3D8A11; border: 1px solid #f2f2f2;"><i class="fa fa-check-circle"></i>Submit</button>'+
                    '</div>');

Sincere thanks for the help. 真诚的感谢您的帮助。 It is greatly appreciated. 非常感谢。

jQuery can operate on items that detached from the DOM, so simply convert your text to a jQuery object and operate on that. jQuery可以对与DOM分离的项目进行操作,因此只需将文本转换为jQuery对象并对其进行操作即可。

var $editArea = $(editArea); //converts text to a jQuery object
$editArea.prepend(fileLink);

If you need to get just the HTML string back: 如果您只需要获取HTML字符串:

$editArea.html()

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

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