簡體   English   中英

從jQuery插件內部訪問公共函數

[英]Accessing public functions from inside a jQuery plugin

這是我第一次沒有教程就編寫jQuery插件。 現在(2014年9月28日),jQuery網站無法正常工作(我不知道為什么),所以我在那里找不到任何資源。

以下是報告錯誤的插件的一部分:

$(function($){
    $.fn.dialog = function(command, options) {
        var opts = $.extend( {}, $.fn.dialog.defaults, options );
        //code
        $.fn.dialog.handleCancel = function() {

        };
        $.fn.dialog.handleAccept = function() {

        };
        return this;
    };

    $.fn.dialog.defaults = {
        // some other props
        onCancel: $.fn.dialog.handleCancel(),
        onAccept: $.fn.dialog.handleAccept()
    };
    // code
}(jQuery));

當我調用插件( $("#dialog1").dialog(/*..*/) )時,瀏覽器控制台顯示以下內容:

Uncaught TypeError: undefined is not a function

該錯誤與onCancel: $.fn.dialog.handleCancel()

如何訪問這些方法,它們應該在哪里? (我也希望他們可以訪問$(this) <-對話框本身)

在調用$.fn.dialog函數之前, handleCancelhandleAccept函數不會初始化。 因此,當您設置對話框默認值時,它們是未定義的。

$.fn.dialog.defaults之前插入以下代碼:

$.fn.dialog();

嘗試重新排列塊中的塊,添加過濾器,以防止默認情況下同時 handleCancelhandleAccept 例如,

 (function($){ $.fn.dialog = function(command, options) { var $el = this; // access , pass arguments to methods $.fn.dialog.handleCancel = function(c) { $el.html(c + "led") }; $.fn.dialog.handleAccept = function(a) { $el.html(a + "ed") }; // call `handleCancel` or `handleAccept` , // based on `command` $.fn.dialog.defaults = { // some other props onCancel: command === "cancel" ? $.fn.dialog.handleCancel(command) : null, onAccept: command === "accept" ? $.fn.dialog.handleAccept(command) : null }; var opts = $.extend( {}, $.fn.dialog.defaults, options ); //code return this; }; // code }(jQuery)); $("button").on("click", function(e) { $("#result").dialog(e.target.id) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button id="accept">accept</button><button id="cancel">cancel</button><br /> Result: <div id="result"></div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM