use underscore.js list functions on collection of jquery objects

匿名 (未验证) 提交于 2019-12-03 02:26:02

问题:

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.

回答1:

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") 


回答2:

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"); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!