jQuery 在 append 到 DOM 之前从元素中生成变量

标签 jquery string variables append store

努力提高效率。在将元素 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/

相关文章:

javascript - 禁用网页元素

jquery - 附加一个带有延迟的点击功能

javascript - jquery.nav.js 一点击后不起作用

C程序: Strcmp

javascript - 将字符串转换为 float javascript

java - Java中如何获取字符串的最后x行?

python - 如何在python中将变量转换为字符串

javascript - 我怎样才能知道哪个元素从js触发了事件?

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

variables - 无法删除 sysmis spss 变量