gpt4 book ai didi

无法从 jquery 对象调用的 Javascript 方法?

转载 作者:数据小太阳 更新时间:2023-10-29 04:44:42 24 4
gpt4 key购买 nike

我正在阅读 Learning jQuery 1.3(Jonathan Chaffer 和 Karl Swedberg),在对表进行排序时,他们在调用 .sort() 之前使用了 .get(),并说

we need to transform jQuery objects into array of DOM nodes. Even though jQuery objects act like arrays in many respects , they don't have any of the native array methods available, such as .sort().

代码:

$("#sort").click(function() {
var posts = $("#posts_div .post");
posts.sort(function(a, b) {
return ($(a).text()) > ($(b).text());
});
$.each(posts, function(index, post) { $("#posts_div").append(post); });
});​

所以我尝试在不使用 .get() 的情况下做到这一点,但令人惊讶的是即使没有 .get() 最新的 jQuery 它也能工作,但没有用1.3

所以做了一些 fiddle 来弄清楚

**Not working without .get() jquery 1.2.6 **

Working with .get() jquery 1.2.6

Working without .get() jquery 1.7.2

Working with .get() jquery 1.7.2

很明显早期的 jQuery 对象没有像 Javascript 数组一样具有 .sort() 功能?但现在他们有..

所以我的问题是 jQuery 对象尚不支持哪些功能,因此我们可以记住在使用前转换为 Javascript 数组??

最佳答案

jQuery 对象目前支持 3 种数组方法:

var methods = 'pop push reverse shift sort splice unshift concat join slice toString indexOf lastIndexOf filter forEach every map some reduce reduceRight'.split(' ')
var implemented = $.grep(methods, function(m) {
return $.prototype[m] == Array.prototype[m];
});
console.log(implemented); // => ["push", "sort", "splice"]

它们也有 slice,但它与数组的 slice 不同:

$.prototype.slice === Array.prototype.slice // => false

关于无法从 jquery 对象调用的 Javascript 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11158102/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com