jQuery在追加到DOM之前使变量脱离元素

tec*_*ant 7 string variables jquery store append

试图在这里提高效率.在将元素附加到DOM之前,如何将元素存储为变量?看起来创建它是一种浪费,附加它,然后再找到它来制作一个变量.

我的方法如下.OBV它将字符串保存为变量,而不是对象,但是你明白了.

对我来说有什么魔力,还是我必须做两次旅行?

var $rGallery = '<section id="rGallery" />';

$bin.before($rGallery);

console.log($rGallery);
Run Code Online (Sandbox Code Playgroud)

Jas*_*wne 11

.before().append()可以将jQuery对象作为参数.您只需创建新对象,将其存储在变量中,然后将其传递给.before().append().

快速举例:

<div id="bin"> </div> ​​​​​​​​​​​​​​​​​​​​

var newElement;

$(document).ready(function() {

   newElement = $("<button>New button</button>");
   $("#bin").append(newElement);

   alert(newElement.text());
});?
Run Code Online (Sandbox Code Playgroud)