我已经使用 jQuery 几年了并且非常喜欢它。但是,我的项目中有很多函数,我想将它们作为扩展的 jQuery 函数。
对于这个例子,我将使用 $.post 函数来演示我何时尝试用我自己的函数完成:
$.post('file.php', { arg1: 'hi', arg2: 'hi2' }, function ( data ) {
// Is called after function completes
// and returns a value (in this case data)
});
我认为这个函数应该是什么样子
(function( $ ) {
$.fn.popup = function( options ) {
options = $.extend( $.fn.popup.defaults, options );
if ( options.type === 1 )
var opt = '<table><tr><td><div id="pConfirm">CONFIRM</div></td><td><div id="pCancel">CANCEL</div></td></tr></table>';
$('body').prepend('<div class="overlay-control"></div>');
$('body').prepend('<div class="info-overlay"><h1>'+title+'</h1>'+ message + opt +'</div>');
$(document).on('click', 'pConfirm', function () {
//callback would happen here and would return a value
});
$(document).on('click', 'pCancel', function () {
//callback would happen here and would return a value
});
});
怎么称呼
$.popup('title', 'message', 'type', function(ret) {
if ( ret === 0 )
//Cancelled
else
//Accepted
}
我希望有人可以发布一个支持一些值并能够返回结果的示例,或者为我提供一个好的教程。
干杯!
最佳答案
这是一个允许您传入选项和回调的示例。单击其中一个按钮时执行回调,它接收按钮的类型,例如CONFIRM
或 CANCEL
。
您会注意到我没有使用元素 ID 或类来处理它们。相反,它在创建后保留对元素的引用。这样做的好处是它使它更通用并且不会与其他代码发生类或 ID 冲突。
插件代码:
(function($) {
$.extend({
popup: function(options, callback) {
var container;
function actionClicked(){
var type = $(this).data('type');
container.remove(); // remove the popup from the DOM
callback(type); // execute callback
}
// create buttons under a table
var table = $('<table><tr><td class="confirm"></td><td class="cancel"></td></tr></table>');
table.find('.confirm').append(
$('<button></button>', { type : 'button' })
.data('type', 'CONFIRM')
.text('Confirm')
.click(actionClicked)
);
table.find('.cancel').append(
$('<button></button>', { type : 'button' })
.data('type', 'CANCEL')
.text('Cancel')
.click(actionClicked)
);
// create the popup elements
container = $('<div class="info-overlay"></div>')
.append(
$('<h1></h1>').text(options.title)
)
.append(
$('<p></p>').text(options.message)
)
.append(table);
$('body').prepend(container);
}
});
})(jQuery);
用法:
$.popup({ title : 'my title', message : 'my message', type : 'my type' }, function(action){
console.log("selected action " + action);
if(action == 'CONFIRM'){
// confirmed
} else if(action == 'CANCELLED') {
// cancelled
}
});
关于javascript - jQuery 自定义插件 : returning a value to event,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19583152/