在 jquery 对象集合上使用 underscore.js 列表函数

发布于 2024-12-26 04:33:51 字数 440 浏览 2 评论 0原文

我正在使用一个同时使用 jQuery 和 underscore.js 的应用程序。我希望能够在 jQuery 对象集合上使用一些下划线的迭代器函数,例如 any()all() 。有办法做到这一点吗?我想做类似以下的事情:

checkboxes = $("input[type=checkbox]");
_.filter(checkboxes, function(box) {
    return box.is(":checked");
});

但这会引发错误:

Uncaught TypeError: Object #<HTMLInputElement> has no method 'is'

所以我假设此上下文中的 box 的行为不像 jQuery 对象。

I'm am working with an app that uses both jQuery and underscore.js . I'd like to be able to use some of underscore's iterator functions, such as any() and all() over a collection of jQuery objects. is there a way to do this? I'd like to do something similar to the following:

checkboxes = $("input[type=checkbox]");
_.filter(checkboxes, function(box) {
    return box.is(":checked");
});

but this throws an error:

Uncaught TypeError: Object #<HTMLInputElement> has no method 'is'

so I'm assuming box in this context isn't acting like as a jQuery object.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

許願樹丅啲祈禱 2025-01-02 04:33:51

您必须在 jQuery 中包装 box

checkboxes = $("input[type=checkbox]");
checkboxes = _.filter(checkboxes, function(box) {
    return $(box).is(":checked");
});

box.checked,而不是为集合中的每个元素创建一个新对象:

checkboxes = $("input[type=checkbox]");
checkboxes = _.filter(checkboxes, function(box) {
    return box.checked;
});

此外,您可以只使用本 >旁注: jQuery 有自己的过滤方法

checkboxes = $("input[type=checkbox]").filter(function() {
    return $(this).is(":checked");
});

此外,在您的示例中- 你确定要过滤吗?您可以像选择器一样轻松地使用它:

checkboxes = $("input[type=checkbox]:checked")

You have to wrap box in jQuery:

checkboxes = $("input[type=checkbox]");
checkboxes = _.filter(checkboxes, function(box) {
    return $(box).is(":checked");
});

Also, instead of creating a new object for every single element in the collection, you could just use the native box.checked:

checkboxes = $("input[type=checkbox]");
checkboxes = _.filter(checkboxes, function(box) {
    return box.checked;
});

On a side note: jQuery has its own filter method:

checkboxes = $("input[type=checkbox]").filter(function() {
    return $(this).is(":checked");
});

Furthermore, in your example - are you sure you have to filter? You could just as easily use that as your selector:

checkboxes = $("input[type=checkbox]:checked")
九厘米的零° 2025-01-02 04:33:51

这里 box 是一个 HTMLInputElement 类型对象。它不是一个 jQuery 对象。由于 .is 是一个 jQuery 对象方法,因此您需要来自 <代码>框。

它可以通过$(box)来完成。然后应用.is()

$(box).is(":checked");

Here box is a HTMLInputElement type object. Its not a jQuery object. As .is is a jQuery object method, you need jQuery object from box.

It can be just done by, $(box). Then apply .is().

$(box).is(":checked");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文