javascript 从 jQuery 对象获取值数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5550220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting array of values from jQuery object
提问by bluszcz
I have following object:
我有以下对象:
$("input:checkbox:checked")
[
<input class=?"li_checker" type=?"checkbox" category_uid=?"1.3" category_language=?"da">?,
<input class=?"li_checker" type=?"checkbox" category_uid=?"1.3.1" category_language=?"da">?
]
If there is any helper in jQuery which allows me to get value of "category_uid" for all elements and returns it as the another array? Expected result:
如果 jQuery 中有任何帮助程序允许我获取所有元素的“category_uid”值并将其作为另一个数组返回?预期结果:
["1.3", "1.3.1"]
回答by bpierre
回答by Mathias Bynens
As bpierre suggested, use .map()
. His answer is correct.
正如 bpierre 建议的那样,使用.map()
. 他的回答是正确的。
If you need this behavior for different attributes, you might as well write is as a reusable function (“jQuery plugin”):
如果您需要针对不同属性的这种行为,您不妨将 is 编写为可重用的函数(“jQuery 插件”):
jQuery.fn.pluck = function(attr) {
return this.map(function() {
return this.getAttribute(attr);
}).get();
};
$('input:checkbox:checked').pluck('category_uid'); // ["1.3", "1.3.1"]
P.S. category_uid
is not a valid attribute in HTML. Consider using custom data-*
attributes instead, e.g. data-category-uid="foo"
.
PScategory_uid
不是 HTML 中的有效属性。考虑改用自定义data-*
属性,例如data-category-uid="foo"
.
回答by T.J. Crowder
Just for the fun of it, a thirdway, this one using attr
:
只是为了好玩,第三种方式,这个使用attr
:
var categories = [];
$("input:checkbox:checked").attr("category_uid", function(index, value) {
categories.push(value);
});
Off-topic: If you want to have arbitrary, custom attributes on HTML elements, recommend using the data-
prefix defined by HTML5 (details). You can use it now, even if you're not using the HTML5 doctype (this is one of the places where HTML5 is just codifying — and reining in — current practice), and it future-proofs a bit.
题外话:如果你想在 HTML 元素上拥有任意的自定义属性,建议使用data-
HTML5 定义的前缀(details)。您现在可以使用它,即使您没有使用 HTML5 文档类型(这是 HTML5 只是编纂 - 并控制 - 当前实践的地方之一),并且它有点面向未来。
回答by kapa
回答by russellfeeed
Something like
就像是
var checked_cats = new Array();
$("input:checkbox:checked").each(function() {
checked_cats.push($(this).attr('category_uid'));
});
(not tested)
(未测试)
p.s. saw your tweet.
ps 看到你的推文了。
回答by gion_13
Here's a more "pluginy" way to do this:
这是一个更“插件化”的方法来做到这一点:
(function($){
$.fn.getAttributes = function(attribute){
var result = [];
$(this).each(function(){
var a = $(this).attr(attribute);
if(a)
result.push(a);
});
return result;
}
})(jQuery);
and then use it as follows :
然后按如下方式使用它:
var result = $("input:checkbox:checked").getAttributes("category_uid");
Haven't tested it, but it should work just fine.
还没有测试过,但它应该可以正常工作。