当我尝试使用 .after
构建一系列断开连接的 DOM 节点时,如果它们为空,则可以正常工作:
[14:56:45.186] $('<span></span>').after('<p></p>');
[14:56:45.193] ({0:({}), length:2, prevObject:{0:({}), length:1}, context:(void 0), selector:".after([object Arguments])", 1:({})})
但是如果我尝试在第一个节点中添加任何文本,则会失败:
[14:56:41.521] $('<span>test</span>').after('<p></p>');
[14:56:41.525] ({0:({}), length:1})
如果我将该结果分配给一个变量并尝试检查它,则看起来好像 after
根本没有被调用过。
这是怎么回事?我该如何解决?
<小时/>编辑:对于那些感兴趣的人,我最终编写了以下包装器,这似乎使我的生活变得更加轻松:
function tag(name) {
return function(contents, options) {
var o = options || {};
var is_array = $.type(contents) === "array";
if (!is_array) {
o.text = contents;
}
result = $('<' + name + ' />', o);
if (is_array) {
$.each(contents, function(i, child) { result.append(child); });
}
return result;
}
}
var span = tag('span');
var div = tag('div');
最佳答案
为了澄清您的错误 - 当我在 JavaScript 控制台中运行您的代码时,我得到以下信息:
> $('<span></span>').after('<p></p>');
[<span></span>,<p></p>]
> $('<span>test</span>').after('<p></p>');
[<span>test</span>]
根据the jQuery 1.9 upgrade guide :
Prior to 1.9, .after(), .before(), and .replaceWith() would attempt to add or change nodes in the current jQuery set if the first node in the set was not connected to a document, and in those cases return a new jQuery set rather than the original set. This created several inconsistencies and outright bugs--the method might or might not return a new result depending on its arguments! As of 1.9, these methods always return the original unmodified set and attempting to use .after(), .before(), or .replaceWith() on a node without a parent has no effect--that is, neither the set or the nodes it contains are changed.
所以:您观察到的行为是由于使用 .after()
导致的错误。在没有父节点的节点上。从 1.9 开始,jQuery 开发团队通过使用 .after()
完全删除它来解决了这种不一致问题。这种方式应该始终返回没有 <p>
的初始节点在它之后( fiddle )。
解决方法:
将 DOM 节点推送到一个简单的数组上。或者将它们附加到父节点,然后获取所有子节点:( fiddle )
$chain = $('<div>').append('<span></span>').append('<p>qwer</p>').children();
关于jquery - 如何连接非空、断开连接的节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14345919/