我想从我的插件中调用一个外部函数,我希望外部函数可以 读取被调用按钮的值date-id。
plugin.js
;(function ($, window, document, undefined) {
// Function-level strict mode syntax
'use strict';
$.fn.Plugin = function(options) {
var options = $.extend({}, $.fn.Plugin.defaults, options);
return this.each(function() {
var $this = $(this);
$.each(options.commands, function(el, fc) {
$this.on('click', '.' + el, function(e) {
//options.callback.call(fc);
});
});
});
};
$.fn.Plugin.defaults = {
commands: {
add: "addFunc",
edit: "editFunc",
del: "deleteFunc",
show: "showFunc"
},
callback: function() {}
};
})(jQuery, window, document);
的index.php
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="js/plugin.js"></script>
<script>
$(function() {
$('#grid').Plugin();
});
function editFunc() {
alert($(this).attr('data-id'));
}
</script>
</head>
<html>
<body>
dinamic table
<table>
<tr>
<td>001</td>
<td>
<button type="button" class="btn btn-warning btn-xs edit" data-id="001"><span class="glyphicon glyphicon-edit"></span></button>
<button type="button" class="btn btn-danger btn-xs delete" data-id="001"><span class="glyphicon glyphicon-trash"></span></button>
</td>
</tr>
<tr>
<td>002</td>
<td>
<button type="button" class="btn btn-warning btn-xs edit" data-id="002"><span class="glyphicon glyphicon-edit"></span></button>
<button type="button" class="btn btn-danger btn-xs delete" data-id="002"><span class="glyphicon glyphicon-trash"></span></button>
</td>
</tr>
...
</table>
我怎么能这样做?谢谢
答案 0 :(得分:1)
editFunc()
应设置在全局范围(或插件范围)上,不包含在文档伪就绪处理程序中,您的选项应该是函数引用,而不是字符串。
所以:
$.fn.Plugin = function (options) {
var options = $.extend({}, $.fn.Plugin.defaults, options);
return this.each(function () {
var $this = $(this);
$.each(options.commands, function (el, fc) {
$this.on('click', '.' + el, function (e) {
fc.call(this);
});
});
});
};
$.fn.Plugin.defaults = {
commands: {
add: addFunc,
edit: editFunc,
"delete": deleteFunc, // 'delete' is a reserved word
show: showFunc
},
callback: function () {}
};
$(function () {
$('table').Plugin();
});
function editFunc() {
alert('call editFunc');
}