在具有相同类且是直接兄弟的两个 DIV 之间插入新 DIV
现在正在与这个问题斗争一段时间。我的标记简化了:
<div class=row>
<div class="somediv"></div>
<div class="somediv2"></div>
<div class="elem"></div>
<div class="elem"></div>
<div class="somediv3"></div>
<div class="somediv4"></div>
<div class=row>
....
我需要找到一种方法来选择文档上的所有 DIV,以便: 1.有一个类:elem 2.他们的下一个DIV也有类名:elem。 然后我需要在它们之间插入一个新的 DIV:
<div class=row>
<div class="somediv2"></div>
<div class="elem"></div>
<div class="new"></div>
<div class="elem"></div>
<div class="somediv3"></div>
<div class="somediv4"></div>
<div class=row> // and it goes...
$(document).ready( function () {
if($('.elem').next().hasClass('.elem')) {
$('<div class="new"></div>').appendTo().prev('.elem');
} else {
});
});
Struggling with this one for a while now. My markup simplified:
<div class=row>
<div class="somediv"></div>
<div class="somediv2"></div>
<div class="elem"></div>
<div class="elem"></div>
<div class="somediv3"></div>
<div class="somediv4"></div>
<div class=row>
....
I need to find a way to select all DIVs on document ready that:
1. has a class: elem
2. their next DIV also has the class name: elem.
Then I need to insert a new DIV between them:
<div class=row>
<div class="somediv2"></div>
<div class="elem"></div>
<div class="new"></div>
<div class="elem"></div>
<div class="somediv3"></div>
<div class="somediv4"></div>
<div class=row> // and it goes...
$(document).ready( function () {
if($('.elem').next().hasClass('.elem')) {
$('<div class="new"></div>').appendTo().prev('.elem');
} else {
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
它使用 CSS 的相邻同级选择器 (
+
)。它找到一个类.elem
的元素,以及紧邻其前面的另一个类.elem
的元素,然后在其前面添加一个新的 div。小提琴:http://jsfiddle.net/4r2k4/
Try this:
It's using CSS's adjacent sibling selector (
+
). It finds an element with class.elem
with another element with class.elem
immediately preceding it, then adds a new div before it.Fiddle: http://jsfiddle.net/4r2k4/
非 jQuery 解决方案:
现场演示: http://jsfiddle.net/2MfgB/ 2/
“但是 Šime,这在 IE8 中不起作用...”
:P
更新:
替代解决方案:
现场演示: http://jsfiddle.net/2MfgB/3/< /a>
The non-jQuery solution:
Live demo: http://jsfiddle.net/2MfgB/2/
"But Šime, this doesn't work in IE8..."
:P
Update:
Alternative solution:
Live demo: http://jsfiddle.net/2MfgB/3/
你的代码对我来说看起来很不错。难道你不需要把它包装在一个
each
中,这样它就可以在每一个上触发吗?Your code looks pretty good to me. Don't you just need to wrap it in a
each
so that it fires on each one?