开发者

Beginner Javascript: jQuery 'toggle' problem

HI All,

I'm a veritable JS beginner and thus I've been using some simple bits of jQuery to help give me the effects I want. All has been going well until I tried to implement a jQuery toggle effect. I want the code to apply to multiple elements and so I'm trying to slim it down and make it generic rather than writing a line for each toggle tab.

I just can't seem to get it to work!

Head w/ javascript:

<head>
<title>My Title</title>
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.3.0/build/cssreset/reset-min.css" />
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
    $('#content div[id^=toggle]').hide();
    $('[class^=info]').click(function() {
        var x = $(this).attr("idName");
        $('#toggle_' + x).toggle();
        return false;
        });
    });
</script>

</head>

Body:

<div id="content">
    <div class="info_tab" id="info_grover">
        <img src="images/pgrover_120x137.jpg" alt="Philip Grover" />
        <h1>Philip Grover</h1><br />
        <p>Info about Philip Grover</p>
    </div>
    <div id="toggle_info_grover">
    </div>
    <div class="info_tab" id="info_lewis">
        <img src="images/rlewis_120x137.jpg" alt="Roy Lewis" />
        <h1>Roy Lewis</h1><br />
        <p>Info about Roy Lewis</p>
    </div>
    <div id="toggle_info_lewis">
    </div>
</div>

I know the answer is probably extremely simple and I suspect it has something to do with my usage of the "this" keyword but af开发者_开发技巧ter an hour of searching I can't seem to work it out for my specific scenario. I'd really appreciate any advice.

Thanks in advance,

Rich


Your code is looking for an attribute called "idName", and yet none of your HTML elements have that attribute. I think you want just "id".

    var x = $(this).attr("id");

or, more simply,

    var x = this.id;


This is complicated, by the way. If your "toggler" is always the next element, you'd better use a class like "toggler" of the clickable element (nothing else, no IDs, no nothing) and use:

$('.toggler').click( function() {
$(this).prev().toggle();
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜