在各个 div 上使用 jquery 切换
我正在尝试使用 + 和 - 框创建切换效果来显示和隐藏 div。示例 http://theodin.co.uk/tools/tutorials/jqueryTutorial/index .html
这是我正在使用的脚本
$(function(){
$('.block').hide();
$('#show').toggle(function(){
$('.block').show();
$(this).attr("src","images/minus.jpg" );
},function(){
$('.block').hide();
$(this).attr("src", "images/plus.jpg" );
});
});
HTML
<div id="show"> Open <img id="show" src="images/plus.jpg"/> </div>
<div class="block">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
</div>
它适用于一个 div,但我有多个,当我单击一个时,它们都会显示。有没有办法使用我拥有的代码单独切换它们?
I'm trying to create a toggle effect using + and - boxes for showing and hiding divs. And example http://theodin.co.uk/tools/tutorials/jqueryTutorial/index.html
This is the script I'm using
$(function(){
$('.block').hide();
$('#show').toggle(function(){
$('.block').show();
$(this).attr("src","images/minus.jpg" );
},function(){
$('.block').hide();
$(this).attr("src", "images/plus.jpg" );
});
});
The HTML
<div id="show"> Open <img id="show" src="images/plus.jpg"/> </div>
<div class="block">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
</div>
It works fine with one div but I have multiple and when I click one, they all show. Is there a way to toggle them individually using the code I have?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将
show ID
更改为class
,如下所示:然后 jQuery 变为:
这是一个例子。
Change the
show ID
to aclass
like this:Then the jQuery becomes:
Here's an example.
您正在更改
#show
元素的src
,而您应该在其子上更改它。
这使用
.children()
获取子元素,以便您可以更改其源。
此外,
与其父级具有相同的 ID。这是不允许的。 ID 必须是唯一的。
You're changing the
src
of the#show
element, when you should be changing it on its child<img>
.This uses
.children()
to get the child<img>
element so you can change its source.Also, the
<img>
has the same ID as its parent. This is not allowed. IDs must be unique.