检查一下:
jQuery("document").ready (function($){
var matchesEl = ".para a:has(img), .para iframe"
$('.wrapper940').each(function(index){
if ($(this).find(matchesEl).length > 0) {
$('<ul>').insertBefore($(this).children('.title'));
$(this).find(matchesEl).each(function() {
//The line code under will only works if all your .wrappers940 always have at least one matched element.
//$("<li>").append($(this)).appendTo($('.wrapper940 ul').eq(index));
//So the right code is:
$("<li>").append($(this)).appendTo($('.wrapper940').eq(index).children('ul'));
});
}
$('p').filter(function () { return $.trim(this.innerHTML) == "" }).remove();
});
});
评论代码:
1)如果你只想移动图像,你可以使用.para img
,但我认为你想移动元素<a>
与<img>
,所以你可以使用:.para a:has(img)
.
2) The index
这里的变量$('.wrapper940').each(function(index){
在这一行中匹配正确的 ul 很重要:$("<li>").append($(this)).appendTo($('.wrapper940 ul').eq(index));
3)该行将删除空白<p>
tags: $('p').filter(function () { return $.trim(this.innerHTML) == "" }).remove();
将他们的内容移入后<li>
s
代码笔:http://codepen.io/anon/pen/wDmsi http://codepen.io/anon/pen/wDmsi
回答评论中的问题:
1) The index
是匹配的元素的索引号each()
。基数是 0。因此,如果页面中有 10 个 .wrapper940,第一个的索引 = 0,第二个的索引 = 1,直到最后一个和第 10 个的索引 = 9。我们在这里使用它来强制代码不将 img 和 iframe 发送到错误的 .wrapper940。它说来自 .wrapper940 索引 6 的 img 和 iframe 属于 .wrapper940 索引 6。写这篇文章时我刚刚发现我的代码失败。检查上面的代码以查看更改。
2)我一直用this
对于纯 JavaScript 和$(this)
对于jquery.这好像是$(this)
有更多属性,就像我们在这里看到的那样:jquery中$(this)和this的区别 https://stackoverflow.com/questions/3633270/difference-between-this-and-this-in-jquery但使用$(...)
消耗更多的处理。因此,您始终可以测试两者是否适用于每种情况并仅使用this
.
3)你可以简化:
var newUl = $("<ul></ul>");
newUl.insertBefore($(this).children('.title'));
To
$('<ul></ul>').insertBefore($(this).children('.title'));
并且从这到
$('<ul>').insertBefore($(this).children('.title'));
4)功能appendTo()
, insertBefore()
而相似已经是一种回声。我相信如果该元素存在,jQuery 就会移动它。如果它不存在,jQuery 将创建它,但我无法最终确认。
5)这个清除的技巧<p>
标签对我来说也很神奇。我不知道它到底是如何工作的。我从这里得到了代码:使用 jQuery 删除“空”段落 https://stackoverflow.com/questions/7823914/remove-empty-paragraphs-with-jquery