最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery if object is present - Stack Overflow

programmeradmin3浏览0评论

I have a script that copies the text from an image's ALT-text and makes a caption box, and inputs the text.

var alt = $("#hoejre p span img").attr("alt");
$('#hoejre p span img').after('<span></span>');
$('#hoejre p span span').html('<strong>' + alt.replace('-', '</strong> <em>') + '</em>');

This works great, when there IS an image. But when there aren't any images, the script fails in IE7.

How can I wrap the VAR with an IF sentence.

I have a script that copies the text from an image's ALT-text and makes a caption box, and inputs the text.

var alt = $("#hoejre p span img").attr("alt");
$('#hoejre p span img').after('<span></span>');
$('#hoejre p span span').html('<strong>' + alt.replace('-', '</strong> <em>') + '</em>');

This works great, when there IS an image. But when there aren't any images, the script fails in IE7.

How can I wrap the VAR with an IF sentence.

Share Improve this question asked Nov 12, 2010 at 11:38 curly_bracketscurly_brackets 5,59815 gold badges62 silver badges103 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

why call a method when you could just look at length property?

if ($imgs.length) {
  ... /* one or more images exist */
}

The size() method:

if ($("#hoejre p span img").size() > 0)
{
  var alt = $("#hoejre p span img").attr("alt");
  $('#hoejre p span img').after('<span></span>');
  $('#hoejre p span span').html('<strong>' + alt.replace('-', '</strong> <em>') + '</em>');
}

jQuery selectors return an array.

You can check whether it contains any elements with the native JS Array.length property. Base your if on whether the length is >0.

You can check how many objects a jQuery selector returns with .size()

Check fcalderan's answer, which suggests using the .length property instead.
It has the same result, but is potentially faster.

For example you can do the following:

var $imgs = $("#hoejre p span img");
if( $imgs.size() > 0 ) {
    var alt = $imgs.attr("alt"); 
    $('<span></span>').html('<strong>' + alt.replace('-', '</strong> <em>') + '</em>')
                      .insertAfter( $imgs );
}
发布评论

评论列表(0)

  1. 暂无评论