jQuery 对象和循环的问题

发布于 2024-12-08 03:47:18 字数 1879 浏览 4 评论 0原文

我现在正在创建一个 jQuery 插件,它将

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()
        });
    }

所以我获取选项,然后将它们排序到一个数组中,当我将该数组推送到我的控制台时,我得到以下内容,

[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", name="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"}]

我的第一个问题是如何从数组中删除所有具有值的内容0 因为我的插件替换了第一个条目如果用户也告诉它,则在我对如何获取选项进行一些更改之前,我使用了以下内容,

options.splice(0, 1);

但选项不再存在,所以我不能只删除每个数组的第一个条目,其次我需要附加值和名称添加到我的新下拉列表中,但是我遇到了问题,

我目前正在使用此代码附加值,

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>');
}

但是这会将我在控制台中看到的所有 3 个对象添加到第一个下拉列表中,其中 2 个对象我在控制台中看到的对象到第二个对象, 1 人反对最终的下拉菜单。

我需要将第一个对象添加到第一个下拉列表中,将第二个对象添加到第二个下拉列表中,将第三个对象添加到第三个下拉列表中,依此类推。

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", name="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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

℡Ms空城旧梦 2024-12-15 03:47:18

对于第一个问题,您可以使用 jQuery.grep()函数过滤数组的元素。

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

对于你的第二个问题,我可能会按照(如果我理解正确的话)使用 < code>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()
    );
});

基本上:

  1. jQuery 具有用于过滤和迭代原始 JS 数组的内置功能。
  2. 缓存您要插入到 DOM 中的 HTML 模板(以便 jQuery 不必在每次将其添加到文档时执行整个“选择”shebang)
  3. 出于同样的原因,也缓存下拉选择。

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.
感性 2024-12-15 03:47:18

您可以从列表中过滤出 value property 等于 0 的所有对象,方法如下:

/**
 * 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);

现在您必须过滤您的 select_options 列表(这是一个列表列表):

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

然后,您必须将正确的 options 列表附加到其各自的 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>';
}

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>';
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文