Jquery - 插件的保留元素
Jquery - reserve element of the plugin
我正在尝试做一个使用 this.each 方法之外的一些函数的简单插件
我想在同一页面的两个元素上使用,但我遇到了问题,因为它引用了
相同的 table 个元素。
;(function ($, window, document, undefined) {
'use strict';
function init() {
makeHeader.call(this);
$('<p>footer</p>').insertAfter('table');
}
function makeHeader() {
$('<p>header</p>').insertBefore('table');
}
$.fn.MYPlugin = function(options) {
var options = $.extend(true, {}, defaults, options);
return this.each(function() {
var $this = $(this);
init.call(this);
$this.on('click', 'th', function() {
alert('Hallo!');
});
});
};
})(jQuery, window, document);
js
$(function() {
$('#tbl').MYPlugin();
$('#tbl2').MYPlugin();
});
html
<table id="tbl" class="table table-condensed table-hover table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Code</th>
<th>Name</th>
<th>Phone</th>
</tr>
</thead>
</table>
<table id="tbl2" class="table table-condensed table-hover table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Code</th>
<th>Name</th>
<th>Phone</th>
</tr>
</thead>
</table>
我怎样才能使插件仅在初始化元素(#tbl 或#tbl2)的保留上下文中工作,以便您可以在同一页面上的多个项目上使用它?
谢谢
您不厌其烦地通过调用 init.call(this)
进行初始化,但未能在 init()
中使用 this
,而是将其传递给 makeHeader()
... 它所在的位置也没有使用!
尝试:
function init() {
makeHeader.call(this);
$('<p>footer</p>').insertAfter(this);
}
function makeHeader() {
$('<p>header</p>').insertBefore(this);
}
我正在尝试做一个使用 this.each 方法之外的一些函数的简单插件 我想在同一页面的两个元素上使用,但我遇到了问题,因为它引用了 相同的 table 个元素。
;(function ($, window, document, undefined) {
'use strict';
function init() {
makeHeader.call(this);
$('<p>footer</p>').insertAfter('table');
}
function makeHeader() {
$('<p>header</p>').insertBefore('table');
}
$.fn.MYPlugin = function(options) {
var options = $.extend(true, {}, defaults, options);
return this.each(function() {
var $this = $(this);
init.call(this);
$this.on('click', 'th', function() {
alert('Hallo!');
});
});
};
})(jQuery, window, document);
js
$(function() {
$('#tbl').MYPlugin();
$('#tbl2').MYPlugin();
});
html
<table id="tbl" class="table table-condensed table-hover table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Code</th>
<th>Name</th>
<th>Phone</th>
</tr>
</thead>
</table>
<table id="tbl2" class="table table-condensed table-hover table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Code</th>
<th>Name</th>
<th>Phone</th>
</tr>
</thead>
</table>
我怎样才能使插件仅在初始化元素(#tbl 或#tbl2)的保留上下文中工作,以便您可以在同一页面上的多个项目上使用它? 谢谢
您不厌其烦地通过调用 init.call(this)
进行初始化,但未能在 init()
中使用 this
,而是将其传递给 makeHeader()
... 它所在的位置也没有使用!
尝试:
function init() {
makeHeader.call(this);
$('<p>footer</p>').insertAfter(this);
}
function makeHeader() {
$('<p>header</p>').insertBefore(this);
}