我正在尝试将类为 .books_inarticle_list
的元素从其在倒数第二个 H2 之前的原始位置移动。
我正在使用无法正常工作的以下内容:
$('.books_inarticle_list').insertBefore('#content_column > h2:nth-last-child(2)');
另一方面,类似这样的方法可行:
$('.books_inarticle_list').insertBefore('#content_column > h2:nth-of-type(6)');
所以问题一定出在 nth-last-child()
选择器上,但我不明白它可能是什么。
有没有人看到该代码有任何问题或知道将该元素移动到倒数第二个 H2 标签之前的替代方法?
最佳答案
试试 .get()
method , 支持负数倒转。
$('.books_inarticle_list').insertBefore($('#content_column > h2').get(-2));
编辑 转念一想,遵循您自己的示例并使用 :nth-last-of-type()
selector 更有意义, 这将是相反的。
$('.books_inarticle_list').insertBefore('#content_column > h2:nth-last-of-type(2)');
:nth-last-child()
对您不起作用的原因是,:nth-child()
指的是他们在 DOM 中的 sibling ,而不是选择器返回的元素列表。
关于javascript - 使用jQuery将元素移动到倒数第二个h2之前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42518318/