ahmet yılmaz
ahmet yılmaz

Reputation: 3

jquery load once

I have this code:

<script>   
$(document).ready(function () {
    $('#lnk').click(function(e) {
        e.preventDefault();
        url = $(this).attr('href');
        $("#content").load(this.href);
    });

});
</script>

<a href="http://google.com" id="lnk">Google</a>
<a href="http://gmail.com" id="lnk">Gmail</a>
<div id="content">

</div>

When I click the first link (google) it works and load content to my content div. However, when I click second link (gmail) it doesn't work.

Can anybody help me understand this behavior?

Upvotes: 0

Views: 652

Answers (2)

gen_Eric
gen_Eric

Reputation: 227200

IDs are unique, you cannot have multiple elements with the same ID ($('#lnk') will get the 1st element). Use classes instead

<script>   
$(document).ready(function () {
    $('.lnk').click(function(e) {
        e.preventDefault();
        $("#content").load(this.href);
    });

});
</script>

<a href="http://google.com" class="lnk">Google</a>
<a href="http://gmail.com" class="lnk">Gmail</a>

Also, this will not work, as you cannot use .load to load arbitrary URLs. That's called the same origin policy.

Upvotes: 1

PCasagrande
PCasagrande

Reputation: 5402

JQuery is attaching the event to the first thing that has the ID you specified, as the document should only have one element with that ID. Try this instead:

<script>   
$(document).ready(function () {
    $('.lnk').on('click', function(e) {
        e.preventDefault();
        $("#content").load(this.href);
    });

});
</script>

<a href="http://google.com" class="lnk">Google</a>
<a href="http://gmail.com" class="lnk">Gmail</a>
<div id="content">

</div>

Upvotes: 1

Related Questions