开发者

issues with a jQuery object and looping

I am creating a jQuery plugin at the moment, which turns a <select> into a pretty dropdown menu, I having a little bit of a problem though, I can get the options of the selects on a page, by doing this,

var self = $(this);
    name = self.attr('name');
    select_options = $(this).children();
    // an array so that we can related options together
    sorted_options = [];
    //loop through the options sorting them into the array as we go.
    for(i=0;select_options.length>i;i++) {
        sorted_options.push({
            'value': select_options.eq(i).val(),
            'name': select_options.eq(i).text()
        });
    }

So I am getting the options and then sorting them into an array, when I push this array to my console I get the following,

[Object { value="0", name="I'm looking for..."}, Object { value="1", name="actors"}, Object { value="2", name="presenters"}, Object { value="3", name="voice overs"}]
[Object { value="0", name="Skill"}, Object { value="1", name="actors"}, Object { value="2", name="presenters"}, Object { value="3", name="voice overs"}, Object { value="4", na开发者_如何学Gome="dancers"}, Object { value="5", name="accents"}, Object { value="6", name="film"}, Object { value="7", name="tv"}]
[Object { value="0", name="Gender"}, Object { value="1", name="male"}, Object { value="2", name="female"}]

My first question is how can I remove from the array everything that has a value of 0 as my plugin replaces the first entry from a dropdown if the users tells it too, before I made some changes as how I got the options, I used the following,

options.splice(0, 1);

But options no longer exists, so I cannot just remove the first entry of each array, secondly I need to append the values and names to my new dropdowns, however I am having problems with this,

I am using this code to append the values at the moment,

for(i=0;sorted_options.length>i;i++) {
    $('.dropdown dd ul').append('<li <a href="#"><span class="option">'+ sorted_options[i]['value'] + '</span><span class="value">' + sorted_options[i]['name'] + '</span></a></li>');
}

however this adds all of 3 objects that I see in my console to the first dropdown, 2 of the objects I see in my console to the second object, and 1 object to the final dropdown.

I need to add the first object to first dropdown, the second to the second and the third to the third, etc.


For your first question, you can use jQuery.grep() function to filter through the elements of an array.

var filteredArray = $.grep(rawArray, function(v,i) {
    return (v.value === '0' ? null : v);
});

For your second question, I'd probably do this along the lines of (if I understand you correctly) using jQuery.each:

var template = $(
    '<li><a href="#"><span class="option"></span><span class="value"></span></a></li>'
), dropdown = $('.dropdown dd ul');

// notice that the args of $.grep and $.each are reversed
$.each(filteredArray, function(i,v) {
    // add the (i)th object to the (i)th dropdown
    dropdown.eq(i).append(
        template.clone()
            .find('.option').text(v.value).end()
            .find('.value).text(v.name).end()
    );
});

So basically:

  1. jQuery has built-in functionality for filtering and iterating through raw JS arrays.
  2. Cache the HTML template you're inserting into the DOM (so that jQuery doesn't have to go through the whole "selecting" shebang everytime you add it to the document)
  3. Cache the dropdown selection as well, for the same reasons.


You can filter from a list, all objects having the value property equals to 0 in this way:

/**
 * Remove from a list all object having `obj.value` == value (ex. 0).
 *
 * @param {Object} value The value to avoid.
 * @param {Array:Object} A list of objects.
 * @return {Array:Object} The new filtered Array.-*emphasized text*
 */
function filterByValue(value, list) {
   var newlist = [],
       obj,
       max,
       i;

   for (i = 0, max = list.length; i < max; i += 1) {
      obj = list[i];

      if (obj.value !== value) {
         newlist.push(obj);
      }
   }
}

var newList = filterByValue(0, list);

Now you've to filter your select_options list (which is a list of lists):

function filter_selectOptions(select_options) {
   var sortedOptions;
       max,
       i;

   for (var i = 0, max = select_options.length; i < max; i += 1) {
      sortedOptions = select_options[i];
      sortedOptions = filterByValue(0, sortedOptions);             
   }
}

Then, you've to append the right options list to its respective select.

var uls = document.getElementsByClassName("dropdown").
                  .getElementsByTagName("dd").
                  .getElementsByTagName("ul");

for (var i = 0, max = uls.length; i < max; i += 1) {
   ul = uls[i];

   sortedOptions = sortedOptions[i];

   ul.innerHTML = '<li <a href="#"><span class="option">'+ sortedOptions[i]['value'] + '</span><span class="value">' + sortedOptions[i]['name'] + '</span></a></li>';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜