jQuery检查前置是否失败 [英] JQuery check if prepend failed
本文介绍了jQuery检查前置是否失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
关于如何测试prepend()是否成功的任何想法? Prepend()当然不适用于图像标签,因此我需要执行before().
Any ideas on how I would test if prepend() succeeds? Prepend() doesn't work on an image tag of course so I need to perform before().
我正在尝试使用.query类在所有跨度之前添加图像,但无法使其在包含自封闭标签(如图像)的跨度上工作.
I'm trying to prepend an image to all spans with a class of .query, but cannot get it to work on spans that contain self closing tags like images.
尝试过:
$('.query').each(function(i) {
var elm=$(this);
if (elm.prepend('<img class="fold" src="/img/fold.png" />').find('img.fold').length==0) {
elm.before('<img class="fold" src="/img/fold.png" />');
}
});
开启:
<span class="query">
<img alt="blah" src="img/banner.jpg" height="422" width="952" />
</span>
<span class="query">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ornare, tellus in posuere viverra, dui dolor lacinia elit, vitae vestibulum nuluris condimentum. Donec vel mauris t sed sit amet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos</p>
</span>
没有答案,所以我现在可以解决:
No answers so I have a work around for now:
if (elm[0].tagName.toLowerCase()=="img") {
elm.before('<img class="fold" src="/img/fold.png" />');
}
else {
elm.prepend('<img class="fold" src="/img/fold.png" />')
}
推荐答案
因为我无法检测到prepend是否失败,所以我检测到prepend是否会失败.
Since I you cannot detect if prepend fails I detected if prepend will fail with.
if (elm.is(':empty')) {
elm.before('<img class="fold" src="/img/fold.png" />');
}
else {
elm.prepend('<img class="fold" src="/img/fold.png" />');
}
这篇关于jQuery检查前置是否失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文