有没有办法使这个jQuery脚本动态? [英] Is there a way to make this jquery script dynamic?
问题描述
我正在使用此jquery代码在页面上显示和隐藏div.如您所见,我限制为5个div.有没有办法使它们动态化?
I'm using this jquery code to show and hide divs on my page. As you can see, I an limited to 5 divs. Is there a way to make them dynamic?
$(document).ready(function() {
$('.box').hide();
$('a.toggle').click(function() {
$('.box').toggle(400);
return false;
});
});
<a href="#" class="toggle" title="Show Comments"><img src="images/read.gif" alt="" /></a>
<div class="box" class="comment">hidden content</div>
这是我修改后的代码
$(function () {
$('div.box').hide();
$('a.toggle').click(function () {
$(this).next('div.box').toggle(400);
});
});
<div class="entry">
<h3>Title</h3>
<p>content</p>
<p class="posted">Posted by Admin<br />
<a href="#" class="toggle">
<img src="read.gif" alt="" />
</a>
</div>
<div class="box" class="comment">Hidden</div>
推荐答案
看看您的标记,您可以执行以下操作:
Looking at your markup, you could do something like this:
$(document).ready(function () {
$('div.box').hide();
$('a.toggle').click(function () { // all A elements with class 'toggle'
$(this).next('div.box').toggle(400); // toggle the next DIV with class 'box'
});
});
基本上将点击处理程序绑定到您的所有具有类toggle
的链接,然后在单击它们时,它将寻找下一个兄弟姐妹(相对于被点击的链接 ),该兄弟姐妹是<类box
的c1>,并使用 Traversing/next 函数.
Basically bind a click handler to all your links with class toggle
, and then when they are clicked, it will look for the next sibling (relative to the clicked link) that is a div
with class box
, using the Traversing/next function.
在标记此处中查看上述示例.
Check the above example with your markup here.
我检查了您的标记,并且您的.toggle
链接嵌套在div.entry
元素内,并且还有一个未封闭的段落,因此我再次将代码调整为您的标记:
I reviewed your markup, and your .toggle
links are nested inside a div.entry
element, also there is an unclosed paragraph, so I've adjusted the code to your markup again:
$(function () {
$('div.box').hide();
$('a.toggle').click(function () {
$(this).parents('.entry').next('div.box').toggle(400);
});
});
您会注意到,我在寻找div.entry
元素,因为.box是它们的兄弟.
You will notice that I look for the div.entry
element, since the .box are siblings of them.
在此处中查看更新示例.
这篇关于有没有办法使这个jQuery脚本动态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!