2017-03-16 47 views
0

我有以下代碼:jQuery選擇爲「本」迴歸

function checkBoxOpenStatus(clickedBox) { 
    if($("#productsBox").hasClass("boxOpen")) { 
     closeBox(obj.productsBox.bx, clickedBox); 
     delay = 200; 
    } else if($("#fabricationBox").hasClass("boxOpen")) { 
     closeBox(obj.fabricationBox.bx, clickedBox); 
     delay = 200; 
    } else if($("#aboutPBBox").hasClass("boxOpen")) { 
     closeBox(obj.aboutPBBox.bx, clickedBox); 
     delay = 200; 
    } else { delay = 0; } 

我的目標是評估三個盒子,如果他們中的一個具有類「boxOpen」,那麼我就需要關閉該對話框,給我的「openSelectedBox」函數添加一個延遲(上面不存在)。我的問題是,我可以在上面的代碼更改爲以下幾點:(?沒有鬆動發送特定選擇的能力)

if($("#productsBox" || "#fabricationBox" || "#aboutPBBox").hasClass('boxOpen') { 
     closeBox(obj.(**WHAT SELECTOR CAN GO HERE??**).bx, clickedBox); 
     delay = 200; 

我知道「或」評估工作,但我不知道該怎麼使用該「或」定義的實例通過適當的選擇來激發「closeBox」函數。我寧願學習,所以請給我一個選擇器可以在那裏工作的解釋,同時執行這樣的評估。

+0

什麼'obj'?爲什麼你調用的函數不存在('closeBox','openSelectedBox')?製作一個獨立的樣本。 – Tomalak

+0

實際上,您的評估或評估不起作用,因爲它只返回第一個字符串。在控制檯console.log(「first」||「second」||「three」);'中檢查。它只檢查第一個框的類。其他2個被忽略。 –

回答

0

您注意到重複的代碼塊並希望優化它們。 (插入我喜歡你這裏的meme)。

你可以這樣來做:

// This will get the 3 elements in a jQuery object and filter the 3 elements to only keep the ones that have the class "boxOpen" 
var theOnesWithTheClass = $("#productsBox, #fabricationBox, #aboutPBBox").filter(".boxOpen"); 

// This will call the closeBox with the id of each element inside the jQuery object. I do it this way just in case there are more than 1 element. 
// The jQuery each method will call the function setting the this context to each element inside the jQuery object. 
theOnesWithTheClass.each(function() { 
    closeBox(obj[this.id].bx, clickedBox); 
}); 

// This will set the delay to 200 only if there are elements inside the jQuery object. The ? conditional returns the block before the : if true and the block after it if false. 
delay = theOnesWithTheClass.length > 0 ? 200 : 0; 
+0

我明白有些東西不合適。我正在學習javascript,html,css和jquery,並且只使用有限的Internet。感謝您的詮釋。 – sirjackk1888

+0

@ sirjackk1888編號:P –

0

使用一個選擇器,將所有框與類相匹配。如果這返回至少1個元素,那麼有一個打開的框,你可以得到這個元素的ID。

然後,您可以使用另一個選擇器來獲取具有該類的元素的ID。

var openBoxes = $("#productBox.boxOpen, #fabricationBox.boxOpen, #aboutPBBox.boxOpen"); 
if (openBoxes.length > 0) { 
    var openId = openBoxes.attr("id"); 
    closeBox(obj[openId].bx, clickedBox); 
    delay = 200; 
} else { 
    delay = 0; 
} 

如果您將所有這些框都設置爲普通類,而不必在選擇器中列出所有ID,那將會更簡單一些。

+0

你可以像下面提到的那樣使用jQuery來獲得所有具有類「boxopen」的輸入。像這樣$(「。boxopen」)。這樣你就不必做任何事情了。我會更新我的代碼。 –