0

how can i tell jquery to use the <a id=""> or <a href=""> as a URL to load on click? For example URL page1.php. either by getting the href, or by getting the id and then appending .php

html

<a id="page1" class="load" href="page1.php">1</a>
<a id="page2" class="load" href="page2.php">2</a>
<a id="page3" class="load" href="page3.php">3</a>

jquery

<script>
    $(document).ready(function () {  
        $(".load").click(loadDynamic);  
    });  
    function loadDynamic() {  
        $("#load_in")  
            .load("",function (content) {  
                $(this).hide().fadeIn("slow");  
                return false;  
        }); 
    }  
</script>
arboles
  • 1,321
  • 4
  • 20
  • 39
  • [This][1] answers your question perfectly. [1]: http://stackoverflow.com/questions/1694595/can-i-call-jquery-click-to-follow-an-a-link-if-i-havent-bound-an-event-hand – Dhaivat Pandya May 28 '12 at 21:50

3 Answers3

3

Use this.href to get the href.

$(document).ready(function() {
    $(".load").click(loadDynamic);
});

function loadDynamic() {
    $("#load_in").load(this.href, function(content) {
        $(this).hide().fadeIn("slow");
    });
        return false;
}​

Of course you can use this.id + ".php" as well.

Note that you wrote return false inside the load callback thus it won't prevent the default anchor click! You should move it to the outer scope like in the answer.


For those of you complaining about .click(fn) against on('click', fn)

Those are the same function, .click(fn) is an alias for on('click', fn):

In the first two variations, this method is a shortcut for .bind("click", handler), as well as for .on("click", handler) as of jQuery 1.7.

jQuery docs

gdoron
  • 147,333
  • 58
  • 291
  • 367
  • @Lix. They are the same. `click` is an alias to it. Read the docs: `In the first two variations, this method is a shortcut for .bind("click", handler), as well as for .on("click", handler) as of jQuery 1.7.` – gdoron May 28 '12 at 21:53
3

You can use this.href:

$(".load").click(function() {
    $("#load_in").load(this.href, function() {
        $(this).hide().fadeIn("slow");
    });
    return false;
});

To get ID use simple this.id.

VisioN
  • 143,310
  • 32
  • 282
  • 281
0

Replace

.load("",function (content) {

With

.load(this.href, function (content) {
David Hellsing
  • 106,495
  • 44
  • 176
  • 212