2014-09-02 84 views
0
$.fn.example = function() { 
    $.getJSON("example.json", function(json){ 
    //1 
    }); 
}; 

$("div").example(function() { 
    $(this).text(json.text); //2 
}); 

我想做這樣的事情。 #2必須在#1中運行。調用帶插件功能的jQuery插件

回答

0

我推測你使用的是jquery_example插件。

根據您的代碼,您想要的示例文本位於json.text。在這種情況下,您可以在回調函數中初始化它:

$.fn.example = function() { 
    $.getJSON("example.json", function(json){ 
     $("div").example(json.text); 
    }); 
}; 
1

因此,在參數中定義一個變量並使用它?

$.fn.example = function(callback) { 
    var cb = callback ? $.proxy(callback, this) : function(){}; 
    var txt = $(this).text().toUpperCase(); 
    $.getJSON("example.json", function(json){ 
     cb(json); 
    }); 
}; 

$("div").example(function (json) { 
    $(this).text(json.text); //2 
}); 

http://learn.jquery.com/plugins/basic-plugin-creation/#accepting-options

+0

我得到「語法錯誤」 – mutlucan96 2014-09-03 05:13:21

+0

我編輯它,這不是一個插件的正常模式。 – epascarello 2014-09-03 12:45:57

+0

瀏覽器控制檯: ReferenceError:json未定義 – mutlucan96 2014-09-03 15:11:05