2017-07-30 28 views
0

我正在使用右/左按钮移动图像的项目的小样本库,方法是移除并重新分配类以进行标识,然后将图像附加到显示元素。jQuery有条件的,否则语句无效?

我曾尝试为我的变量之一引入一个if/else条件语句,其中“else”语句旨在选择与活动图像相对的图像(如果它位于数组的末尾)(如果说活动图像是图库中的最后一个图像,我希望else语句为RIGHT按钮选择第一个图像)。 然而,我的声明的else语句不起作用,并且活动类被分配给DOM中下一行的任何元素。

HTML:

<h2>Random Image Gallery</h2> 

     <div id="display"></div> 

    <div class="active slider" id="slide1"> 
     <img src="images/482.jpg" alt="random image boats"> 
     <p>Boats on a River</p> 
    </div> 

    <div class="slider" id="slide2"> 
     <img src="images/1109-600x376.jpg" alt="random image"> 
     <p>Grey Landscape</p> 
    </div> 

    <div class="slider" id="slide3"> 
     <img src="images/1648jpg" alt="random image3"> 
     <p>River Dock</p> 
    </div> 

<article> 

     <button id="lbutton">Left</button> 

     <button id="rbutton">Right</button> 

    </article> 

的JavaScript(与意见对有关条件语句):

jQuery("#rbutton").on("click", function() { 
    "use strict"; 

    var active = jQuery("div#gallerybox > div.active"); 
    //"else" conditional is inert? 
    var next = active.next("div.slider") ? active.next("div.slider") : jQuery("div#slide1"); 

    var nextImage = next.find("img").clone().addClass("dis"); 

    var display = jQuery("div#display"); 

    var prevDisImg = display.find("img.dis ~ img.dis") ? display.find("img:first-of-type") : null() ; 

    nextImage.appendTo("div#display"); 

    prevDisImg.remove();     

    next.addClass("active"); 

    active.removeClass("active"); 


}); 
     //This button works 
jQuery("#lbutton").on("click", function() { 
    "use strict"; 

    var active = jQuery("div#gallerybox > div.active"); 

    var previous = active.prev("div.slider").length ? active.prev("div.slider") : jQuery("div#gallerybox > div:last"); 

    var prevImage = previous.find("img").clone().addClass("dis"); 

    var display = jQuery("div#display"); 

    var nextDisImg = display.find("img.dis + img.dis") ? display.find("img:last-of-type") : null(); 

    prevImage.appendTo("div#display"); 

    nextDisImg.remove(); 

    previous.addClass("active"); 

    active.removeClass("active"); 

}); 

我在哪里我的 “其他” 声明回事? 或者我会以错误的方式执行条件?

+0

请提供一个小提琴这样人们可以轻松地运行你的代码。 –

+1

@ J.C.Rocamonde一个堆栈片段... –

+0

@Jonasw我想知道使用不是堆栈片段的外部Web服务有什么问题。 –

回答

1

jQuery的总是返回一个新的jQuery对象,更有耐力truthy所以youre做这样的:

var result = {} ? "truthy":" objects are never falsy"; 

您可以检查jQuery集合的length属性:

var previous = active.prev("div.slider").length ? active.prev("div.slider") : jQuery("div#gallerybox > div:last"); 
+0

谢谢你做了我的左键功能的工作。研究正确使用类似的委托人。 –

+0

@mister先生会工作,但空不是一个功能... –

+0

谢谢我发现非常shorly,.length可以适用于两个选择器和应用所需的结果。 您是否认为'null'else语句在这里是必需的? –