另一个关于函数的 jQuery 菜鸟问题
我想“功能化”更多的 jQuery 代码,而不是编写小的独立片段。 这是一个例子。 假设我有一些想用作触发器的 li,如下所示:
<li class="alpha-init" id="a-init">A</li>
<li class="alpha-init" id="b-init">B</li>
<li class="alpha-init" id="c-init">C</li>
还有一些我想根据这些触发器的点击来隐藏和显示的内容,如下所示:
<ul id="a-sub" class="alpha-popdown">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<ul id="b-sub" class="alpha-popdown">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<ul id="c-sub" class="alpha-popdown">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
如果我想为以下内容编写一个小片段对于每种情况,我都可以这样做:
$('li.alpha-init #a-init').click(function(){
$('ul#a-sub').slideToggle(200);
}
但这意味着编写与链接和子菜单集一样多的片段。 我怎样才能将其写入函数中? 我不想“吃一天”,所以只要您觉得可以写下尽可能多的解释,我们将不胜感激。 非常感谢!
I want to "functionalize" more of my jQuery code, instead of writing little standalone snippets. Here's an example. Let's say I have some li's that I'd like to use as triggers, like so:
<li class="alpha-init" id="a-init">A</li>
<li class="alpha-init" id="b-init">B</li>
<li class="alpha-init" id="c-init">C</li>
And some stuff I'd like to hide and show in correspondence to clicks on those triggers, like so:
<ul id="a-sub" class="alpha-popdown">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<ul id="b-sub" class="alpha-popdown">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<ul id="c-sub" class="alpha-popdown">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
If I wanted to write a little snippet for each case, I could do:
$('li.alpha-init #a-init').click(function(){
$('ul#a-sub').slideToggle(200);
}
But that means writing as many snippets as there are sets of links and submenus. How can I write this into a function? I'm not looking to "eat for a day", so as much explanation as you feel up to writing would be much appreciated. Thanks very much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您是否考虑过使用 jQuery UI 选项卡 来实现此目的? 这听起来几乎和你想要的一模一样。 您可以设置与默认选项卡不同的样式!
Have you considered using jQuery UI Tabs for this? It sounds nearly exactly like what you want. You can just style the tabs differently than the default!
首先,id 在您的页面上应该是唯一的。 您只需使用选择器
$('#a-init')
即可访问它。我会这样写(对于每个项目):
html:
然后将 jquery 编写为:
基本思想是使用 $(this) 方法访问被单击的项目并选择相对于父级的菜单元素元素。
First off, id's should be unique on your page. You only need to use the selector
$('#a-init')
to access it.I would write that like so (for each item):
html:
And then write the jquery as:
The basic idea would be to use the $(this) method to access the item that was clicked and select your menu element relative to the parent element.
我结合使用了 Artem Barger 和 John Sheehan 的代码。 感谢大家的帮助; 现在我要睡觉了!
I used a combination of Artem Barger and John Sheehan's code. Thanks everyone for your help; now I get to sleep!