我有一堆Wordpress文章,当浏览器小于一定的大小时,我需要将每个帖子中的一个元素移动到另一个元素中(这是一个设计要求)。
我使用下面的代码循环遍历每个帖子,并将元素post-comments移动到post-meta div中。
jQuery('.post-entry').each(function(){ // Loop through each post...
if( jQuery(this).find('.post-meta .post-comments').length == 0 ) {
jQuery(this).find('.post-extra span.post-comments').appendTo('.post-meta'); // Move categories into the ".post-meta" div
jQuery(this).find('.post-extra span.post-comments').remove();
}
});接下来是JSFiddle,但是当前的行为是,第一个post-entry工作得很好,post-comments元素被移动到post-meta中并从原来的位置移除,但是在其他post-entry div上,post-comments元素并没有从它原来的位置被移除--有人知道为什么吗?
基本上,我需要将post-comments从最初的位置移到我正在处理的页面上的多个帖子上的一个名为post-meta的元素中。
发布于 2014-07-08 10:17:21
jQuery('.post-entry').each(function() {
var $post = jQuery(this),
$meta = $post.find('.post-meta');
if ($meta.find('.post-comments').length == 0) {
$post.find('.post-extra .post-comments').appendTo($meta);
}
});这里的不同之处在于,我已经确保您总是在$(this)中找到并附加。您的长度检查是检查所有的.post-entry,而您的appendTo是附加到 all .post-meta的,所以当它第二次遍历循环时,长度检查将不是0。
如果您这样做,您根本不需要.remove,因为appendTo 移动它。
发布于 2014-07-08 09:52:48
移动第一个帖子之后,下面的检查总是失败的,因为它检查第一个元素(您已经移动了):
if( jQuery('.post-entry').find('.post-meta .post-comments').length == 0 )相反,写:
if( $(this).find('.post-meta .post-comments').length == 0 )因为在$().each()循环中,this引用结果节点列表的当前元素:
错:
jQuery('.post-entry').each(function(){ // Loop through each post...
if( jQuery('.post-entry') // <- does not reference the current element正确:
jQuery('.post-entry').each(function(){ // Loop through each post...
if( $(this) <- always references your current element of the each loop发布于 2014-07-08 09:50:41
试试这个
jQuery(this).find('.post-extra span.post-comments').parent().remove(); https://stackoverflow.com/questions/24628642
复制相似问题