Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have many of spans witch represent different objects. How can I write my jQuery code in one function?

HTML:

<div id="rzuty10p" class="rzuty">
            <span id="c_10_01" class="mieszkanie" title=""></span>
            <span id="c_10_02" class="mieszkanie" title=""></span>
            <span id="c_10_03" class="mieszkanie" title=""></span>
            <span id="c_10_04" class="mieszkanie" title=""></span>
            <span id="c_10_06" class="mieszkanie" title=""></span>
            <span id="c_10_05a" class="mieszkanie" title=""></span>
            <span id="c_10_05b" class="mieszkanie" title=""></span>
        </div>      
        <div class="karta">
            <div class="kartaPanel">
                <button class="close">zamknij</button>
                <a class="pdf" href="img/rzuty/mieszkania/001.pdf" onclick="this.target='_blank'">pobierz</a>
            </div>
            <img src="img/rzuty/mieszkania/001.png" alt="mieszkanie 001" />
        </div>

jQuery:

$('#c_10_01').click(function () { 
        $('.pdf').attr({ 
          href: "img/rzuty/mieszkania/001.pdf"
        });
        $('.karta img').attr({ 
          src: "img/rzuty/mieszkania/001.png",
          alt: "mieszkanie 001"
        });
    });

    $('#c_10_02').click(function () { 
        $('.pdf').attr({ 
          href: "img/rzuty/mieszkania/002.pdf"
        });
        $('.karta img').attr({ 
          src: "img/rzuty/mieszkania/002.png",
          alt: "mieszkanie 002"
        });
    });

    $('#c_10_03').click(function () { 
        $('.pdf').attr({ 
          href: "img/rzuty/mieszkania/003.pdf"
        });
        $('.karta img').attr({ 
          src: "img/rzuty/mieszkania/003.png",
          alt: "mieszkanie 003"
        });
    });
share|improve this question

1 Answer

up vote 3 down vote accepted

You can replace it with something like this:

$(".mieszkanie").click(function() {
    var num = this.id.replace(/c_10_0/, "");
    $('.pdf').attr({ 
        href: "img/rzuty/mieszkania/00" + num + ".pdf"
    });
    $('.karta img').attr({ 
        src: "img/rzuty/mieszkania/00" + num + ".png",
        alt: "mieszkanie 00" + num
    });
});

This code uses the class name to install the click handler on all elements and then it gets the number from the id of the clicked on element and derives the various other properties from that id number.

share|improve this answer
so simple, i have to remember this, thx mate – gidzior Aug 13 '12 at 11:58

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.