【问题标题】:JQuery calling the functionJQuery调用函数
【发布时间】:2014-07-31 21:00:50
【问题描述】:

我对 Javascript/JQuery 非常陌生,我正在阅读我同事的代码。他在一个网站上创建了一个非常常见的“常见问题解答”列表,其中不会立即显示答案,只有问题,直到用户单击箭头,然后才会显示答案。

我想弄清楚他是如何做到这一点的。我了解所有 HTML 和 CSS(看起来不错),但我似乎无法理解如何让 Jquery 工作或当用户按下问题上的箭头以显示答案时在哪里调用代码。

他似乎使用的代码在底部。再一次,所有的 HTML 和 CSS 都是链接在一起的,所以我认为这只是如何使用代码的问题。

如果有人可以提供任何帮助,将不胜感激。

谢谢!

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

【问题讨论】:

  • $(this).next().toggle().closest("li").toggleClass("arrow_up") - 就在那里 - 它说从被点击的元素中找到下一个元素,切换它的可见性,找到最近的父母 li 并切换类“arrow_up”
  • @tymeJV 感谢您的快速回复。是的,我认为这正在发生,我只是很困惑将这段代码放在哪里?在常规脚本标记中或页面加载时或...?
  • 它将进入一个 DOM 就绪事件 $(document).ready(function() { - 或在 body 的末尾 - 以上所有代码都是 anchor 元素上的处理程序。
  • @tymeJV 谢谢!完美运行!

标签: javascript jquery html


【解决方案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
});

我有一个完整的提炼和注释复制in this jsFiddle link

他还使用return false 的简写形式。请注意,他的事件处理程序的主体都在一行上。他本可以将它分成两行,但他使用comma operator 使它只适合一行。

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

从 jQuery 事件处理程序返回 false 会阻止事件到达 DOM 中的父元素。

【讨论】:

  • 感谢您的分解!
【解决方案2】:

意思是:

//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

在此处查看与您正在寻找的完全相同的示例“Bootstrap Collapse”:

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

还提供了一个演示代码,您可以了解如何处理。

【讨论】:

    猜你喜欢
    • 2014-11-10
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多