2
我想從我的插件中調用一個外部函數,我希望外部函數能夠讀取調用的按鈕的值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>
我怎麼能這樣做呢?謝謝
我想你建議,但我得到這個錯誤:類型錯誤:fc.call不是一個函數。 –
否則,您可以通過從options.commands中創建動態回調來完成此操作? –
@PaoloRossi在這裏工作:http://jsfiddle.net/aho6mtd9/現在檢查你的代碼中的'fc',我告訴它不應該是字符串,但函數引用,例如'edit:editFunc,'不'編輯: 「editFunc」'。如果由於某些原因,你想使用字符串(但爲什麼你應該?),那麼你可以使用:'window [fc] .call(this);' –