2012-02-07 47 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