为对象创建 jquery 插件



我想为数组拼接创建一个jquery插件(与push()函数相反(。但是我得到错误

Uncaught TypeError: allfiles.pull is not a function这是我的代码:

$.fn.pull = function (index) {
	this.splice(index-1,1);
}
var allfiles = ['1','2','3','4','5'];
$("div").html(allfiles);
allfiles.pull(1);
$("div").html(allfiles);
.first:before{
content:'Before:';
}
.second:before{
content:'After:';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first"></div>
<div class="second"></div>

因为$.fn.pull扩展了 jQuery 函数列表,所以它不会向对象Array添加方法。要做到这一点,请Array.prototype.pull.在你的原始代码中,Array.pull(allfiles.pull(是undefined的,因为你从未声明过它。

我已经更改了您的代码并将数组包装成 jQuery 函数:$(allfiles).这应该能满足你的需求。

$.fn.pull = function (index) {
	this.splice(index-1,1);
return this.toArray();
}
var allfiles = ['1','2','3','4','5'];
$("div.first").html(allfiles);
allfiles = $(allfiles).pull(1);
$("div.second").html(allfiles);
.first:before{
content:'Before:';
}
.second:before{
content:'After:';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first"></div>
<div class="second"></div>

Stack Snippet with Array.prototype.pull (不推荐*(

Array.prototype.pull = function (index) {
	return this.splice(index-1,1);
}
var allfiles = ['1','2','3','4','5'];
$("div.first").html(allfiles);
allfiles.pull(1);
$("div.second").html(allfiles);
.first:before{
content:'Before:';
}
.second:before{
content:'After:';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first"></div>
<div class="second"></div>

* 不建议使用自定义函数更改 JavaScript 的原始对象,例如Array。行为可以改变,或者像jQuery这样的外部脚本可以依赖于相同的名称。pull非常通用。至少使用一个myproject_pull的卑鄙的名字.

最新更新