![](/img/trans.png)
[英]On click add class to element with certain class and remove it from all other elements with same class
[英]remove() not removing element from all parent elements of same class
我有大量的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
的元素中。
移动第一个帖子后,以下检查将始终失败,因为它会检查第一个元素(您已移动的元素):
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
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将附加到所有 .post-meta
因此第二次遍历循环时,长度检查将不会为0
。
如果以这种方式进行操作,则在appendTo
移动它时根本不需要.remove
。
试试这个
jQuery(this).find('.post-extra span.post-comments').parent().remove();
如果删除的元素是“孩子”,则可以尝试以下操作:
$('#parentElement').children().remove(); //For all childs
$('#parentElement').children('div').remove(); //For all childs that are divs
$('#parentElement').children('div.classOfDiv').remove(); //For all childs that are Divs with X class
如果children()
不起作用。 尝试与next()
和closest()
一起玩。 有时候对我有帮助。
提供find()
(过去给我带来了问题find()
一些帮助也可能是:
HTML示例:
<div>
<ul>
<li class="class1"></li>
<button onclick="trigger()">access the li element</button>
</ul>
</div>
如果您想访问li
,也可以尝试一些奇怪的方法,但是可以:
$('this').closest('div').$('.class1').remove(); //When clicking the button, for example
有时候这对我有帮助,因为closest()
在当前位置上方而不是下方查找元素。
我不清楚您要问的是什么,但这也许可以对您有所帮助。
希望对您有所帮助。 祝您好运,并告诉我们情况如何! ;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.