有时我有多个元素需要一个具有一些通用功能的click
回调函数,并且已经实现如下:
function deleteRecord(elem, url, type) {
if (confirm("Are you sure you wish to delete this "+type+"?")) {
$.ajax({
type:'DELETE',
url: url,
dataType: 'json',
success: function (rsp){
$(elem).closest('tr').remove();
},
error: function (xhr) {
alert('Error: '+xhr.responseJSON.message);
}
});
}
}
$("#manual-list img.delete").click(function() { deleteRecord(this, '/1.0/manuals/'+$(this).closest('tr').data('id'),'manual')});
我一直在尝试创建一个非常简单的插件,而不是使用函数。
我已成功创建灵活的 jQuery 插件,如 https://learn.jquery.com/plugins/advanced-plugin-concepts/ 所述但是,我认为对这些类型的应用程序这样做是大材小用,并且希望使用 drop-dead 插件设计模式。我最近的尝试在下面,但是,我没有成功将 url
参数传递给它,该参数是由应用插件的元素派生的。
对于非常简单明了的 jQuery 事件驱动插件,有哪些选项可用?
(function( $ ){
$.fn.deleteRecord = function(url, type) {
console.log('init', url, type, this, url.call(this, url, type));
this.click(function(){
//Confirm that this.each(function(){...}) is not required
console.log('onClick', url, type, this, url.call(this, url, type))
if (confirm("Are you sure you wish to delete this "+type+"?")) {
console.log('onConfirm', url, type, this, url.call(this, url, type))
var e=this;
$.ajax({
type:'DELETE',
url: url.call(this, url, type),
dataType: 'json',
success: function (rsp){
$(e).closest('tr').remove();
},
error: function (xhr) {
alert('Error: '+xhr.responseJSON.message);
}
});
}
})
return this;
};
})( jQuery );
$("#manual-list img.delete").deleteRecord(function(){'/1.0/manuals/'+$(this).closest('tr').data('id')},'manual');
最佳答案
您忘记了 return 语句:
function(){'/1.0/manuals/'+$(this).closest('tr').data('id')}
将其更改为:
function(){return '/1.0/manuals/'+$(this).closest('tr').data('id');}
(function ($) {
$.fn.deleteRecord = function (url, type) {
console.log('init', url, type, url.call(this, url, type));
console.log('----')
this.click(function () {
//Confirm that this.each(function(){...}) is not required
console.log('onClick', url, type, this, url.call(this, url, type))
if (confirm("Are you sure you wish to delete this " + type + "?")) {
console.log('onConfirm', url, type, this, url.call(this, url, type))
var e = this;
$.ajax({
type: 'DELETE',
url: url.call(this, url, type),
dataType: 'json',
success: function (rsp) {
$(e).closest('tr').remove();
},
error: function (xhr) {
alert('Error: ' + xhr.responseJSON.message);
}
});
}
})
return this;
};
})(jQuery);
$("#manual-list img.delete").deleteRecord(function(){return '/1.0/manuals/'+$(this).closest('tr').data('id');},'manual');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="manual-list">
<tr data-id="1">
<td>
<img class="delete" src="https://dummyimage.com/200x200/000/fff&text=1">
</td>
</tr>
</table>
关于javascript - 非常简单的事件驱动 jQuery 插件设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49430708/