我有以下对象:
$("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">?
]
Run Code Online (Sandbox Code Playgroud)
如果jQuery中有任何帮助器允许我为所有元素获取"category_uid"的值并将其作为另一个数组返回?预期结果:
["1.3", "1.3.1"]
Run Code Online (Sandbox Code Playgroud)
bpi*_*rre 21
用途map():
var myArray = $("input:checkbox:checked").map(function(){
return this.getAttribute("category_uid");
}).get();
Run Code Online (Sandbox Code Playgroud)
正如bpierre建议的那样,使用.map().他的回答是正确的.
如果您需要针对不同属性的此行为,您可能还可以将其写为可重用的函数("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"]
Run Code Online (Sandbox Code Playgroud)
PS category_uid不是HTML中的有效属性.请考虑使用自定义data-*属性,例如data-category-uid="foo".
只是为了它的乐趣,第三种方式,这个使用attr:
var categories = [];
$("input:checkbox:checked").attr("category_uid", function(index, value) {
categories.push(value);
});
Run Code Online (Sandbox Code Playgroud)
偏离主题:如果要在HTML元素上拥有任意的自定义属性,建议使用data-HTML5定义的前缀(详细信息).您现在可以使用它,即使您没有使用HTML5文档类型(这是HTML5正在编写的地方之一 - 并且在当前的实践中控制它),并且它将来会有所改进.