如果element包含子元素运行函数

时间:2012-09-18 10:24:19

标签: javascript jquery

我的网站上有一个旋转木马,如果没有元素我的jquery似乎崩溃了。

我没有元素的HTML输出是......

<section class="gallery-viewport-twobedroomapartment viewer">
     <ul>
     </ul>
     <a id="simplePrevious"><img alt="Left Arrow" src="_includes/images/larr.png"></a>
     <a id="simpleNext"><img alt="Right Arrow" src="_includes/images/rarr.png"></a>
</section>

我的jQuery是......

$('.gallery-viewport-twobedroomapartment').carousel('#simplePrevious', '#simpleNext');

是否可以说UL是否包含LI然后运行该函数?

4 个答案:

答案 0 :(得分:1)

if($('.gallery-viewport-twobedroomapartment ul > li').length > 0) {
   $('.gallery-viewport-twobedroomapartment').carousel('#simplePrevious', '#simpleNext');
}

答案 1 :(得分:1)

要知道jQuery集合中是否有任何元素使用length

if ($(elements).length) {
  // there are elements
}

答案 2 :(得分:0)

var liCount = $('ul li').length;

if (liCount > 0) {
  $('.gallery-viewport-twobedroomapartment').carousel('#simplePrevious', '#simpleNext');
}

轰!

答案 3 :(得分:0)

您可以使用.children()length

if ($(".gallery-viewport-twobedroomapartment").children("ul").children("li").length > 1)
    $('.gallery-viewport-twobedroomapartment').carousel('#simplePrevious', '#simpleNext');