簡體   English   中英

jQuery調用函數

[英]JQuery calling the function

我是Javascript / JQuery的新手,我正在研究我的一位同事的代碼。 他在網站上創建了一個非常常見的“ FAQ”列表,在該列表中不會立即顯示答案,只有在用戶單擊箭頭后才顯示問題,然后顯示答案。

我試圖弄清楚他是如何工作的。 我了解所有HTML和CSS(看起來不錯),但是當用戶按下問題上的箭頭以顯示答案時,我似乎無法理解如何使Jquery工作或在何處調用代碼。

他似乎使用的代碼位於底部。 同樣,所有HTML和CSS都已鏈接在一起,所以我認為這只是簡單地使用代碼的問題。

如果有人可以提供任何幫助,將不勝感激。

謝謝!

$("#faq").on("click", "div > a", function() {
        return $(this).next().toggle().closest("li").toggleClass("arrow_up"), !1
    })

讓我為您注釋他的代碼。 它使用一些速記,可能會使初學者感到困惑。

// Select the element with an id attribute of "faq".
// When an <a> which is a first-level child of a div inside of
// #faq is clicked, perform the following actions
$("#faq").on("click", "div > a", function() {
        // "this" references the <a> tag.
        // $(this) wraps it in a jQuery wrapper
        return $(this) 
        // get the next sibling of the <a>. It is our <p>
        .next()
        // switches the element.style.display between none and block
        .toggle()
        // get the nearest parent <li> element.
        .closest("li")
        // add or remove the arrow_up CSS class 
        .toggleClass("arrow_up"), !1 // !1 is a shortcut for false
});

在此jsFiddle鏈接中進行了完整的蒸餾和注釋復制

他還使用簡寫來return false 請注意,他的事件處理程序的主體全部在一行上。 他可以將其分為兩行,但他使用逗號運算符將其僅放在一行中。

$(this).next().toggle().closest("li").toggleClass("arrow_up");
return false; // false === !1;

從jQuery事件處理程序返回false會阻止事件到達DOM中的父元素。

這意味着:

//Bind a click function on every a tag in #faq

$("#faq").on("click", "div > a", function() {

// Toggle Class (so if the closest <li> Element has class "arrow_up" then remove it, otherwise add it)

return $(this).next().toggle().closest("li").toggleClass("arrow_up"), !1

在此處查看示例“引導程序崩潰”,該示例與您正在尋找的示例完全相同:

http://getbootstrap.com/javascript/#collapse

還提供了一個演示代碼,您將了解如何進行處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM