Jquery Function Getvars "rebuild"
i would like to "rebuild" a short snippet:
jQuery.fn.getCheckboxVal = function(){
    var vals = [];
    var i = 0;
    this.each(function(){
        vals[i++] = jQuery(this).val();
    });
    return vals;
}
to such like this:
function getvar() {
       var vals = [];
    var i = 0;
    t开发者_开发百科his.each(function(){
        vals[i++] = $(this).val();
    });
    return vals; 
}
can anybody help to get the "second" works to? (Link to the Full Snippet above: http://trentrichardson.com/2009/01/08/getting-a-list-of-checkbox-values-with-jquery/)
Thanks :)
In the first code, the this keyword points to the jQuery object that you are calling the method on, so you would have to replace that with a jQuery object in the second code:
function getvar(selector) {
  var vals = [];
  var i = 0;
  $(selector).each(function(){
    vals[i++] = $(this).val();
  });
  return vals; 
}
Usage example:
var values = getvar('input:checked');
You can also use the map method to make it simpler:
function getvar(selector) {
  return $(selector).map(function(){
    return $(this).val();
  }).get();
}
I assume you want a function that accepts elements as parameter (here a jQuery object):
function getValues($elements) {
    return $elements.map(function() {
        return $(this).val();
    }).get();
}
Usage:
var values = getValues($('input'));
 加载中,请稍侯......
      
精彩评论