2012-02-07 48 views
1

http://jsfiddle.net/9BCrs/5/链接到外部内容加载到DIV

我有这样的设置使用在左边的DIV两个链接到一个文件加载到一个DIV,但它需要相同的jQuery代码的唯一副本每次有一个新的链接。

有没有办法将被调用的文件和它被调用的DIV通过某种变量连接到链接上,这样代码只能被包含一次?

$(function() { 
$(".link1").click(function() { 
    $(".load_space").load("helloworld.txt", function() { 
     //Insert contents of file wherever 
     $(".block1").stop(true, true).animate({ left: -400 }, 200); 
     $(".block2").stop(true, true).animate({ left: 25 }, 200); 
    }); 
}); 

$(".link2").click(function() { 
    $(".load_space").load("hellouniverse.txt", function() { 
     //Insert contents of file wherever 
     $(".block1").stop(true, true).animate({ left: -400 }, 200); 
     $(".block2").stop(true, true).animate({ left: 25 }, 200); 
    }); 
}); 

$(".link3").click(function() { 
    $(".block2").stop(true, true).animate({ left: 450 }, 200); 
    $(".block1").stop(true, true).animate({ left: 25 }, 200); 
}); 
}); 

回答

1

有一对夫妇的方式。

  1. 在您的代码中使用地图。

    你可以在你的代码的地图,告诉你,link1 =>helloworld.txtlink2 =>hellouniverse.txt,就像这样:

    var map = { 
        link1: "helloworld.txt", 
        link2: "hellouniverse.txt" 
    }; 
    

    然后:

    $(".link1, .link2").click(function() { 
        var file = map[this.className]; // <=== Assumption here, see below 
        $(".load_space").load(file, function() { 
         //Insert contents of file wherever 
         $(".block1").stop(true, true).animate({ left: -400 }, 200); 
         $(".block2").stop(true, true).animate({ left: 25 }, 200); 
        }); 
    }); 
    

    这假定link1link2类将是只有类的元素。如果不是这种情况,在使用它来查找文件之前,您可能需要按一下className。使用data-* attributes

    添加data-file属性您link元素,如:

    <div class="link1" data-file="helloworld.txt">...</div> 
    

    然后:

    $(".link1, .link2").click(function() { 
        var file = $(this).attr('data-file'); 
        $(".load_space").load(file, function() { 
         //Insert contents of file wherever 
         $(".block1").stop(true, true).animate({ left: -400 }, 200); 
         $(".block2").stop(true, true).animate({ left: 25 }, 200); 
        }); 
    }); 
    

    或代替$(".link1, .link2")选择,你可以只使用$("*[data-file]")或更好,但东西有点更有针对性(因为在属性选择器上选择纯粹是有点沉重)。因此,对于具有data-file属性的具有类“链接”的任何元素,或许$(".links[data-file]")

+1

太棒了,我正在使用#2,但我喜欢这两种。很好的帮助。 – Andy 2012-02-07 15:41:23

1

您可以定义函数一次

var load_fct = function() { 
    //Insert contents of file wherever 
    $(".block1").stop(true, true).animate({ left: -400 }, 200); 
    $(".block2").stop(true, true).animate({ left: 25 }, 200); 
} 

而在你需要它重用:

$(".link1").click(function() { 
    $(".load_space").load("helloworld.txt", load_fct); 
}); 
+0

感谢帮助,谢谢。 – Andy 2012-02-07 15:41:44