gpt4 book ai didi

javascript - JQuery 调用函数

转载 作者:行者123 更新时间:2023-12-02 17:08:11 25 4
gpt4 key购买 nike

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

我想弄清楚他是如何做到这一点的。我理解所有的 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
});

我有一个完整的蒸馏和注释复制品 in this jsFiddle link

他还使用了 return false 的简写形式。请注意,他的事件处理程序的主体全部位于一行。他本可以将其分成两行,但他使用了 comma operator使其仅适合一个。

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

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

关于javascript - JQuery 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25068872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com