简体   繁体   中英

Apply to function to multiple elements

HTML:

<div class="container-fluid">
<div class="sidebar">
    <ul class="pills">  
        <li id="l1"><a id="link1">Lesson 1</a></li> <hr>
        <li id="l2"><a href="#" >Lesson 2</a></li> <hr>
        <li id="l3"><a href="#" >Lesson 3</a></li> <hr> 
    </ul>
   <div class="span16" id="target">
</div>

Javascript:

$('#l1').click(function(){
    $('#target').fadeOut('fast', function(){
        $('#target').load("lesson/lesson1.html", function(){
                $('#target').fadeIn('slow');

                });
            });

        });

I have 5 links within my webpage, I was wondering if there was anyway to make this one piece of code instead of copy + pasting it multiple times.

$('a.AjaxLink').click(function(){
    var url = this.href;

    $('#target').fadeOut('fast')
                .load(url, function(){ $(this).stop(true, false).fadeIn('slow'); });
    });

    return false;
});

This code handles the click event for all <a> s with a class of AjaxLink .

In the click handler, it grabs the href , fades out your #target , and performs the AJAX load.

When the AJAX load finishes, it stops the animation (in case the AJAX was faster than the fade), then fades it back in.

Finally, it tells the browser not to take the default action (navigating to the page) by returning false.

Use class instead of id . Select elements using class .
Also you can use .each() method

You could do this with a new jQuery method. Given this HTML:

<a class="hello" href="#">Hello</a>
<a class="goodbye" href="#">Goodbye</a>

<div id="target"></div>

You'd use this code:

jQuery.fn.switchTarget = function( target, href ) {
    var $target = $(target);

    this.bind( 'click', function(e) {
        e.preventDefault();

        $target.fadeOut('fast', function() {
            $target.load( href, function() {
                $target.fadeIn('slow');
            });
        });
    });

    return this;
};

$('.hello').switchTarget( '#target', 'hello.html' );
$('.goodbye').switchTarget( '#target', 'goodbye.html' );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM