jQuery多次附加一个对象 [英] jQuery Appending an Object multiple times

查看:19
本文介绍了jQuery多次附加一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定这里到底发生了什么,我认为变量是一个 jquery 对象.

I am not sure what exactly is happening here, I think the fact that the variable is a jquery object.

这只追加一次,我的问题是为什么?

This only appends once, my question is why?

var newInput = $('<input/>');
$('#newDiv').append(newInput);
$('#newDiv').append(newInput);

虽然这如我所想的那样有效

Though this works as I would assume

var newInput = '<input>';
$('#newDiv').append(newInput);
$('#newDiv').append(newInput);

感谢您的帮助!

推荐答案

当你执行 $(' 时,jQuery 会创建一个 input为您准备的 DOM 元素.

When you do $('<input/>'), jQuery creates an input DOM element for you.

当您 .append() 一个 DOM 元素时,它会将元素从其先前位置分离.(参见小提琴).来自文档:

When you .append() a DOM element, it detaches the element from its previous position. (See Fiddle). From the docs:

如果以这种方式选择的元素被插入到单个位置在 DOM 的其他地方,它将被移动到目标中(未克隆).

If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned).

因此,您的第二次 .append() 调用会将其从最初附加的位置移除,并将其放置在新位置.

Thus, your second .append() call will remove it from where it was appended first and place it in the new position.

当您附加一个字符串时,DOM 元素会在附加时创建.

When you append a string, the DOM element is created as it is appended.

这篇关于jQuery多次附加一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆