开发者

JQuery check if prepend failed

开发者 https://www.devze.com 2022-12-20 09:59 出处:网络
Any ideas on how I would test if prepend() succeeds?Prepend() doesn\'t work on an image tag of course so I need to开发者_如何学Go perform 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开发者_如何学Go perform before().

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.

Tried this:

$('.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" />');
  }
});

On:

<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 does not fail.
If you look in Firebug, you'll see that the element you appended does exist.

You could check whether the newly inserted element .is(':visible'). (Unless the parent itself is hidden)


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" />');
}
0

精彩评论

暂无评论...
验证码 换一张
取 消