[英]Accessing public functions from inside a jQuery plugin
It is the first time I write a jQuery plugin without a tutorial. 这是我第一次没有教程就编写jQuery插件。 Now (September 28 2014), the jQuery site doesn't work (I don't know why), so I cannot find any resource there.
现在(2014年9月28日),jQuery网站无法正常工作(我不知道为什么),所以我在那里找不到任何资源。
Below is part of my plugin that reports errors: 以下是报告错误的插件的一部分:
$(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));
When I call the plugin ( $("#dialog1").dialog(/*..*/)
), the browser console, shows the following: 当我调用插件(
$("#dialog1").dialog(/*..*/)
)时,浏览器控制台显示以下内容:
Uncaught TypeError: undefined is not a function
The error is on the line with onCancel: $.fn.dialog.handleCancel()
. 该错误与
onCancel: $.fn.dialog.handleCancel()
。
How can I access these methods, and where should them be? 如何访问这些方法,它们应该在哪里? (I also want them to have access to
$(this)
<- for the dialog itself) (我也希望他们可以访问
$(this)
<-对话框本身)
Your handleCancel
and handleAccept
functions are not initialized until you call the $.fn.dialog
function. 在调用
$.fn.dialog
函数之前, handleCancel
和handleAccept
函数不会初始化。 Therefore, they are undefined when you set the dialogs defaults. 因此,当您设置对话框默认值时,它们是未定义的。
Insert this code prior to $.fn.dialog.defaults
: 在
$.fn.dialog.defaults
之前插入以下代码:
$.fn.dialog();
Try rearranging blocks within the piece , adding a filter , to prevent both handleCancel
and handleAccept
being called by default; 尝试重新排列块中的块,添加过滤器,以防止默认情况下同时
handleCancel
和handleAccept
; eg, 例如,
(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.