如何从jQuery集合中“弹出"或“转移" [英] How to 'pop' or 'shift' from jQuery set
本文介绍了如何从jQuery集合中“弹出"或“转移"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Javascript中,数组应具有方法 pop 和 shift .
In Javascript, arrays should have methods pop and shift.
但是,JQuery对象似乎缺少以下方法:
However, JQuery objects seem to be missing these methods:
$('div').shift(); // Error, shift is undefined
$('div').pop(); // Error, pop is undefined
$('div').splice(); // Splice is OK actually
我想知道为什么缺少这些功能-毕竟jquery对象只是一个数组.
I wonder why these functions are missing - after all, the jquery object is just an array.
在jquery对象上执行弹出和移位功能的最简单方法是什么?
What's the easiest way of performing pop and shift functions on jquery objects?
推荐答案
它们丢失了,因为jQuery对象不是数组.
They're missing because a jQuery object isn't an Array.
(function( $ ) {
$.fn.pop = function() {
var top = this.get(-1);
this.splice(this.length-1,1);
return top;
};
$.fn.shift = function() {
var bottom = this.get(0);
this.splice(0,1);
return bottom;
};
})( jQuery );
编辑:.slice()
不会修改原始对象.固定为使用.splice()
代替.
.slice()
doesn't modify the original object. Fixed to use .splice()
instead.
这篇关于如何从jQuery集合中“弹出"或“转移"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文