努力提高效率。在将元素 append 到 DOM 之前,如何将其存储为变量?看起来创建它、 append 它、然后再次查找它以创建变量是一种浪费。
我的方法如下。 OBV 它将字符串保存为变量,而不是对象,但您明白了。
对我来说有什么魔力吗?还是我必须去两次?
var $rGallery = '<section id="rGallery" />';
$bin.before($rGallery);
console.log($rGallery);
最佳答案
.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());
});
关于jQuery 在 append 到 DOM 之前从元素中生成变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13963223/