jQuery切换 - 点击切换图标?

5
我正在尝试创建一个jQuery切换播放和暂停图标的功能,我希望能在单击时切换图标。
注意: 我的演示代码可以正常工作,但我想要实现以下功能...如果我单击第一个“播放图标”,它将改变。当我点击第二个“播放图标”时,它将与“暂停图标”一起改变,然后第一个“暂停图标”将改变为“播放图标”,并且它将重复进行第三个图标。
演示代码:

$("#infoToggler").click(function() {
    $(this).find('img').toggle();
});
$("#infoToggler2").click(function() {
    $(this).find('img').toggle();
});
$("#infoToggler3").click(function() {
    $(this).find('img').toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="infoToggler"><img src="http://c28.imgup.net/play-icon223d.png" width="60px" height="60px"/>
<img src="http://e52.imgup.net/stop-icon731e.png" width="60px" height="60px" style="display:none"/>
</div>

<div id="infoToggler2"><img src="http://c28.imgup.net/play-icon223d.png
" width="60px" height="60px"/>
<img src="http://e52.imgup.net/stop-icon731e.png" width="60px" height="60px" style="display:none"/>
</div>

<div id="infoToggler3"><img src="http://c28.imgup.net/play-icon223d.png" width="60px" height="60px"/>
<img src="http://e52.imgup.net/stop-icon731e.png" width="60px" height="60px" style="display:none"/>
</div>

我在Stack Overflow上找到了这些链接,但它们不是我要找的内容。 点击图像时使用jQuery切换 如何在不同按钮单击时使用jQuery切换多个图像?

抱歉,我不太清楚你的问题。 - I'm Geeker
哪些锚点链接? - Jacques Marais
1
@JacquesMarais 没错,看起来像是原帖作者的代码正在运行。 - Adjit
@SayedRafeeq 哦,我明白你的意思了。 - Jacques Marais
@JacquesMarais,我正在尝试实现那个功能。 - Sayed Rafeeq
显示剩余4条评论
1个回答

3

首先,使用类而不是ID进行工作,这样您只需要一个处理程序,而不是多个处理程序。因此,请给div添加类。

接下来,为“重置”图像添加一个类,另一个图像添加另一个类。这使您可以重置其他内容。

然后,您可以向div添加处理程序,以切换该div中的图像并重置所有其他内容:

 $(".toggler").click(function() {
    
        // Reset all images
        $(".toggler img.alt").hide();
        $(".toggler img.orig").show();
        
        // Now toggle the ones in this .toggler
        $("img", this).toggle();
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div class='toggler'>
        <img class='orig' src="http://c28.imgup.net/play-icon223d.png" width="60px" height="60px"/>
        <img class='alt'  src="http://e52.imgup.net/stop-icon731e.png" width="60px" height="60px" style="display:none"/>
    </div>

    <div class='toggler'>
        <img class='orig' src="http://c28.imgup.net/play-icon223d.png" width="60px" height="60px"/>
        <img class='alt'  src="http://e52.imgup.net/stop-icon731e.png" width="60px" height="60px" style="display:none"/>
    </div>

    <div class='toggler'>
        <img class='orig' src="http://c28.imgup.net/play-icon223d.png" width="60px" height="60px"/>
        <img class='alt'  src="http://e52.imgup.net/stop-icon731e.png" width="60px" height="60px" style="display:none"/>
    </div>


太棒了,你理解了我的问题,并且感谢你的解释。我已经查看了你的演示:https://jsfiddle.net/sayedrafeeq/tq3Lvgxh/1/ ...真是太棒了。 :) - Sayed Rafeeq

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接