开发者

cant get jquery toggle function working

trying to swap two images depending on which the user has clicked.

so it should hide the image that the user has just clicked and show the one that was hidden.

must be something simple wrong here...

<!-- toggle for cont开发者_JS百科rast buttons -->
<script type=text/javascript>
        $("a.contrast-button").click(function () {
            $("a.contrast-button").toggle();
        });
</script>



<div class="span-16 last" id="access-controls">
    <a class="contrast-button" id="switchDark" href="#"><img src="/static/images/contrast-dark.png" /></a>
    <a class="contrast-button" id="switchRed" style="display:none;" href="#" ><img src="/static/images/contrast-light.png" /></a>
    <a class="access-nav" href="#">contrast:</a>
</div>


Works as long as you assign the handler on .ready().

Example: http://jsfiddle.net/6NvN8/

 // v------ensures the DOM is ready before running code within
$(function() {
    $("a.contrast-button").click(function() {
        $("a.contrast-button").toggle();
    });
});

If the order of your code is exactly as you show it in the question, then the elements do not exist yet when the jQuery code runs.

If you just flipped it around, it would also make it work.

Example: http://jsfiddle.net/6NvN8/1

<div class="span-16 last" id="access-controls">
    <a class="contrast-button" id="switchDark" href="#"><img src="/static/images/contrast-dark.png" /></a>
    <a class="contrast-button" id="switchRed" style="display:none;" href="#" ><img src="/static/images/contrast-light.png" /></a>
    <a class="access-nav" href="#">contrast:</a>
</div>


<!-- toggle for contrast buttons -->
<script type=text/javascript>
        $("a.contrast-button").click(function () {
            $("a.contrast-button").toggle();
        });
</script>

This is because the elements have a chance to load before your script runs.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜