Link 1

Using jQuery for the first time, simple problem!

I have markup like this:

<p><a id="1" href="#">Link 1</a></p>
<p id="1show" class="starthidden">Hi! I get shown when link 1 is clicked</p>

<p><a id="2" href="#">Link 2</a></p>
<p id="2show" class="starthidden">Hi! I get shown when link 2 is clicked</p>

<p><a id="3" href="#">Link 3</a></p>
<p id="3show" class="starthidden">Hi! I get shown when link 3 is clicked</p>

      

And some javascript like this:

$(document).ready(function(){

    $("#maincontent a").click(function () {
        var id = '#' + $(this).attr("id");
        var show = id + 'show';

        $("id").click(function () {
            $("show").slideToggle("slow");
            return false;
        });

        return false;
    });

});

      

Now id and show are what I expect at runtime, but the following line doesn't work. My guess is the $ ("id") bit - although changing that to $ (id) doesn't work either.

How to fix it?

0


source to share


4 answers


First, the numeric id is not valid HTML. Identity attributes must start with az. I recommend changing your HTML like this:

<p><a href="#msg1">Link 1</a></p>
<p id="msg1" class="starthidden">Hi! I get shown when link 1 is clicked</p>

<p><a href="#msg2">Link 2</a></p>
<p id="msg2" class="starthidden">Hi! I get shown when link 2 is clicked</p>

<p><a href="#msg3">Link 3</a></p>
<p id="msg3" class="starthidden">Hi! I get shown when link 3 is clicked</p>

      

which is valid and understandable. On devices that don't have javascript / css, they additionally move focus to the desired location.



Then you can just pick up the href link after the link:

$(document).ready(function(){

    $("#maincontent a").click(function () {

        var id = $( this ).attr( 'href' );
        $( id ).slideToggle( 'slow' );
        return false;

    });

});

      

+4


source


Variables inside double strings are not parsed like they are in PHP, so you have to do $(show)

. Also, no internal binding click()

is needed - you can simply run slideToggle()

:



$(document).ready(function(){

    $("#maincontent a").click(function () {
        var id = '#' + $(this).attr("id");
        var show = id + 'show';

        $(show).slideToggle("slow");

        return false;
    });

});

      

+2


source


You don't need IDs! Try the following:

$(function(){
    $("a").click(function(){
        $(this).parents("p").slice(0,1).next("p").slideToggle("slow");
    });
});

      

+2


source


Well, I don't see any element with main content ID in the above code. Anyway. I can see this line in your code

$("id").click

      

Why double quotes when you want to access a variable?

0


source







All Articles