更简单的编码方式
在此页面上:我的网站
我有这个 jQuery,但它似乎有点啰嗦。
<script type="text/javascript">
$(document).ready(function(){
$("p").hide();
$("#lastfmrecords").hide();
$("h2.btn1 a").click(function(){
$("ol.btn1>*").toggle(400);
});
$("h2.btn2 a").click(function(){
$("ol.btn2>*").toggle(400);
});
$("h2.btn3 a").click(function(){
$("ol.btn3>*").toggle(400);
});
$("h2.btn4 a").click(function(){
$("ol.btn4>*").toggle(400);
});
$("h2.btn5 a").click(function(){
$("ol.btn5>*").toggle(400);
});
$("h2.btn6 a").click(function(){
$("ol.btn6>*").toggle(400);
});
$("h2.btn7 a").click(function(){
$("ol.btn7>*").toggle(400);
});
});
</script>
<h2 class="btn5"><a href="#">FAVOURITE Books</a></h2>
<ol class="btn5">
<p>Freakonomics, Bad Science, A Brief History of Nearly Everything, 100 years of Solitude, On Chesil Beach</p>
</ol>
然后我有 7 个带有这些名字的有序列表,没有。上面的 5 (btn1 - btn7) 当我点击对应的 H2 标题时会切换。一切都很好,但是有没有办法压缩 jQuery?
On this page: of my website
I have this jQuery, but it seems a bit long winded.
<script type="text/javascript">
$(document).ready(function(){
$("p").hide();
$("#lastfmrecords").hide();
$("h2.btn1 a").click(function(){
$("ol.btn1>*").toggle(400);
});
$("h2.btn2 a").click(function(){
$("ol.btn2>*").toggle(400);
});
$("h2.btn3 a").click(function(){
$("ol.btn3>*").toggle(400);
});
$("h2.btn4 a").click(function(){
$("ol.btn4>*").toggle(400);
});
$("h2.btn5 a").click(function(){
$("ol.btn5>*").toggle(400);
});
$("h2.btn6 a").click(function(){
$("ol.btn6>*").toggle(400);
});
$("h2.btn7 a").click(function(){
$("ol.btn7>*").toggle(400);
});
});
</script>
<h2 class="btn5"><a href="#">FAVOURITE Books</a></h2>
<ol class="btn5">
<p>Freakonomics, Bad Science, A Brief History of Nearly Everything, 100 years of Solitude, On Chesil Beach</p>
</ol>
Then I have 7 ordered lists with those names, no. 5 above (btn1 - btn7) which toggle when I click on the H2 title that corresponds. All works fine, but is there a way of compacting the jQuery?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
其一,您可以将
h2
包裹在div
下,并让您的rel
到您想要切换的ol
类,然后按如下操作,请注意,您可能还想通过传入
event< 来阻止浏览器滚动到顶部/code> 对象作为函数参数并调用
.preventDefault()
编辑:
如果您希望保持布局不变,您还可以执行以下操作:
For one, you can wrap the
h2
's under adiv
and have your<a> rel
to the class of theol
you wanna togglethen do it as below, note that you also might want to prevent the browser to scroll to the top by passing in
event
object as the function argument and call.preventDefault()
EDIT:
If you'd prefer to keep your layout as is, you can also do something like:
for 循环似乎是一个显而易见的解决方案。
A
for
loop seems like an obvious solution.