开发者

Jquery image swap navigation issue

Can someone please tell me what I am doing wrong here?

<script type="text/javascript">
(document).ready(function() {开发者_如何学Python

$j("img.sswap").click(function() {
      $j("img.sswap").each(function() {
            this.src = this.src.replace("_on", "_off");
      });
      this.src = this.src.replace("_on", "_off");
});

});
</script>

<div id="navigation">
<ul>
<li><a href="#d1"><img class="sswap" src="img/d1_off.png"></a></li>
<li><a href="#d2"><img class="sswap" src="img/d2_off.png"></a></li>
<li><a href="#d3"><img class="sswap" src="img/d3_off.png"></a></li>
<li><a href="#d4"><img class="sswap" src="img/d4_off.png"></a></li>
</ul>
</div>


If you simply want to toggle the on/off state of a single image then Alfie-101's answer will work for you. However, from reading your code, it looks like you may only want one image to be "on" at a time. it seems like you're trying to turn "off" all images and then turn "on" the clicked image. The biggest problem in your code is that your last line should be replacing "off" to "on" instead of "on" to "off. So, if you want all images to be "off" then change your code to the following:

$(document).ready(function() {
    $("img.sswap").click(function() {
        $("img.sswap").each(function() {
            this.src = this.src.replace("_on", "_off");
        });
        this.src = this.src.replace("_off", "_on");
    });
});

Working jsFiddle: http://jsfiddle.net/Z8WNZ/


Without knowing what you actually want to happen, this code would appear to swap every image except the one that was clicked. First, you loop through everything that matched the same selector as the bind and swap it. Then you re-swap the one that was clicked, restoring it to it's original state.

I can't believe that's what you actually want to happen, probably you should remove the each loop.


This should do it!

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<div id="navigation">
<ul>
<li><a href="#d1"><img class="sswap" src="img/d1_off.png"></a></li>
<li><a href="#d2"><img class="sswap" src="img/d2_off.png"></a></li>
<li><a href="#d3"><img class="sswap" src="img/d3_off.png"></a></li>
<li><a href="#d4"><img class="sswap" src="img/d4_off.png"></a></li>
</ul>
</div>
<script type="text/javascript">

$(function() {
    $("img.sswap").toggle(
        function() { 
        var src = $(this).attr("src").replace("_off", "_on");
        $(this).attr("src", src);
    },
    function() {
        var src = $(this).attr("src").replace("_on", "_off");
        $(this).attr("src", src);
    });
});
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜