Невозможно получить доступ к параметрам в элементе выбора - PullRequest
0 голосов
/ 10 июля 2020

Проблема : я могу получить объект HTMLOptionsCollection из элемента select, но не могу получить из него точную длину или массив.

Для контекста я пытаюсь создать массив из объекта HTMLOptionsCollection, чтобы я мог oop с помощью параметров добавить выбранный атрибут к одному из элементов параметров. Кроме того, я делаю это для расширения chrome, поэтому я не уверен, возникнут ли из-за этого какие-то странные проблемы с совместимостью.

Прямо сейчас у меня есть этот код:

Вот результаты console.log:

Console log showcasing the unexpected behavior Showcasing the fact that the dropdown.options.length is not accurate at all.

I did not expect the length to be inaccurate at all and can't figure out why this is. Any help is greatly appreciated!

EDIT: Here is my fillDropdown() function. It's ultimate goal is to append option elements to the select element. The extra jargon is to prevent options from getting too long word wise.

  // Input: None
  // Output: None
  // Proceeds to fill the clients dropdown with clients from local storage
  function fillDropdown() {
    chrome.storage.local.get(function(data) {
      if (typeof data.lastClientName !== "undefined") {
        for (var i = 0; i < clients.length; i++) {
          // Create an option element to add to the dropdown.
          var clientOption = document.createElement("option");
          // cutoff is an array which holds whole words. This is done to cleanly cut off a name.
          var cutoff = clients[i].split(" ");
          // A clients name may have no more than 4 words to its name.
          if (cutoff.length > 4) {
            cutoff = cutoff[0] + " " + cutoff[1] + " " + cutoff[2] + " " + cutoff[3] + " ...";
            // The full name attribute is used to store the actual name.
            clientOption.setAttribute("fullName", clients[i]);
            // The value and innerHTML are both the same and are user visible.
            clientOption.setAttribute("value", cutoff);
            if (data.lastClientName === cutoff) {
              dropdown.value = clientOption.value;
            }
            clientOption.innerHTML = cutoff;
          }
          else {
            // fullName is added here for consistency
            clientOption.setAttribute("fullName", clients[i]);
            clientOption.setAttribute("value", clients[i]);
            if (data.lastClientName === clients[i]) {
              dropdown.value = cutoff;
            }
            clientOption.innerHTML = clients[i];
          }
          dropdown.appendChild(clientOption);
        }
      }
      else {
        for (var i = 0; i < clients.length; i++) {
          // Create an option element to add to the dropdown.
          var clientOption = document.createElement("option");
          // cutoff is an array which holds whole words. This is done to cleanly cut off a name.
          var cutoff = clients[i].split(" ");
          // A clients name may have no more than 4 words to its name.
          if (cutoff.length > 4) {
            cutoff = cutoff[0] + " " + cutoff[1] + " " + cutoff[2] + " " + cutoff[3] + " ...";
            // The full name attribute is used to store the actual name.
            clientOption.setAttribute("fullName", clients[i]);
            // The value and innerHTML are both the same and are user visible.
            clientOption.setAttribute("value", cutoff);
            clientOption.innerHTML = cutoff;
          }
          else {
            // fullName is added here for consistency
            clientOption.setAttribute("fullName", clients[i]);
            clientOption.setAttribute("value", clients[i]);
            clientOption.innerHTML = clients[i];
          }
          dropdown.appendChild(clientOption);
        }
      }
    });
  }

Also the only html to be concerned with here is

 

Ответы [ 2 ]

1 голос
/ 10 июля 2020

Попробуйте следующее:

const newArr = Array.from(dropdown.options);
console.log(newArr.length)

Вы можете найти другие способы сделать это здесь: https://hackernoon.com/htmlcollection-nodelist-and-array-of-objects-da42737181f9

0 голосов
/ 10 июля 2020

Мне очень жаль, я только что понял, что клиенты в fillDropdown () не определены. Предполагается, что клиенты - это массив названий компаний, которые я бы использовал для заполнения раскрывающегося списка. Теперь мне любопытно, почему я не получил ошибку в моей консоли. Я думал, что в консоли будет отображаться любая неопределенная переменная.

Помимо того, что клиенты не определены, мне также пришлось сделать fillDropdown функцией обратного вызова.

Спасибо всем за помощь!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...