Почему моя функция PopledRopdown влияет на функциональность Handlesearch?Javascript

Форум по Javascript
Ответить
Anonymous
 Почему моя функция PopledRopdown влияет на функциональность Handlesearch?

Сообщение Anonymous »

Я работаю над системой поиска и фильтрации мебели в JavaScript, где у меня есть два основных блока кода: < /p>

Функция заполненного рода < /strong>:
Эта функция отвечает за динамически заполняющие выпадающие меню с фильтрованными вариантами в качестве предварительного вида пользователя в входное поле. class = "lang-js prettyprint-override">

Код: Выделить всё

function populateDropdown(inputId, dropdownId, options) {
const input = document.getElementById(inputId);
const dropdown = document.getElementById(dropdownId);
let isTextCopied = false;

input.addEventListener('focus', function () {
const query = input.value.toLowerCase();
populateOptions(query, options, dropdown);
if (!isTextCopied) dropdown.style.display = 'block';
});

input.addEventListener('click', function () {
if (!isTextCopied) {
const query = input.value.toLowerCase();
populateOptions(query, options, dropdown);
dropdown.style.display = 'block';
}
});

input.addEventListener('input', function () {
const query = this.value.toLowerCase();
populateOptions(query, options, dropdown);
if (!isTextCopied) dropdown.style.display = 'block';
});

document.addEventListener('mousedown', function (e) {
if (!input.contains(e.target) && !dropdown.contains(e.target)) {
dropdown.style.display = 'none';
}
});

dropdown.addEventListener('mousedown', function (e) {
e.stopPropagation();
});

function populateOptions(query, options, dropdown) {
dropdown.innerHTML = '';
const groupedOptions = {};

options.forEach(option => {
if (option.name.toLowerCase().includes(query)) {
if (!groupedOptions[option.group]) {
groupedOptions[option.group] = [];
}
groupedOptions[option.group].push(option);
}
});

if (Object.keys(groupedOptions).length > 0) {
for (const [group, groupOptions] of Object.entries(groupedOptions)) {
const groupItem = document.createElement('li');
groupItem.className = 'optgroup';
groupItem.textContent = group;
dropdown.appendChild(groupItem);

groupOptions.forEach(option => {
const listItem = document.createElement('li');
let specialtypeKey = (option.name.indexOf('-') > -1) ? parseInt(option.name.split('-')[0].trim(), 10) : option.name;
listItem.innerHTML = `
[img]${option.img}[/img]
${option.name}`;
listItem.setAttribute('data-value', specialtypeKey);

listItem.addEventListener('click', function (e) {
e.stopPropagation();
input.value = option.name;
input.setAttribute('data-selected', specialtypeKey);
dropdown.style.display = 'none';
isTextCopied = true;
});

dropdown.appendChild(listItem);
});
}
} else {
dropdown.style.display = 'none';
}
}

input.addEventListener('input', function () {
if (input.value.length === 0) {
input.value = '';
input.removeAttribute('data-selected');
isTextCopied = false;
}
});

input.addEventListener('click', function () {
if (isTextCopied) dropdown.style.display = 'none';
});
}
< /code>

  Функция Handlesearch < /strong> и поисковые фильтры:
Функция Handlesearch применяет разные фильтры и обновляет отображаемые результаты на основе ввода пользователя.function handleSearch() {
// Obtener los valores de los inputs y filtros con validación
const query = document.getElementById("query").value.toLowerCase();
const selectedLine = (document.getElementById("furniLines").value || "").trim();
const selectedCategory = (document.getElementById("furniCategories").value || "").trim();
const selectedEnvironment = (document.getElementById("furniEnvironments").value || "").trim();
let selectedSpecialtype = (document.getElementById("furniSpecialtypes").value || "").trim();

// Mantener el valor actual de "per_page" directamente desde el input
per_page = parseInt(document.getElementById("per_page_results").value, 10) || 100;

// Procesar el valor de selectedSpecialtype
if (selectedSpecialtype.includes(" - ")) {
selectedSpecialtype = selectedSpecialtype.split("  - ")[0];
}
selectedSpecialtype = selectedSpecialtype ? parseInt(selectedSpecialtype, 10) : "";

// Obtener valores de filtros de tipo de muebles
const allClothingChecked = document.getElementById("allclothing").checked;
const normalClothingChecked = document.getElementById("clothing").checked;
const rareClothingChecked = document.getElementById("rareclothing").checked;
const collectibleClothingChecked = document.getElementById("collectibleclothing").checked;
const collectibleFurniChecked = document.getElementById("furniCollectibles").checked;

const furniWallInput = document.getElementById("furniWall");
const furniFloorInput = document.getElementById("furniFloor");

const selectedFurniType = furniWallInput.checked ? 'wall' : furniFloorInput.checked ? 'floor' : 'none';

// Filtrar por tipo de colección
let filteredData = allFurnis.slice(); // Copiar el array de furnis

// Si "allclothing" está marcado, filtrar solo por "clothingtypes" y sus subcategorías
if (allClothingChecked) {
filteredData = furnidata.clothingtypes.clothingitemtypes.furnitype
.concat(furnidata.clothingtypes.LTDclothingitemtypes.furnitype)
.concat(furnidata.clothingtypes.rareclothingitemtypes.furnitype)
.concat(furnidata.clothingtypes.collectibleclothingitemtypes.furnitype);
} else {
// Si no está marcado, seguir con el flujo normal de filtros
if (collectibleFurniChecked) {
filteredData = furnidata.collectibleitemtypes.furnitype;
} else {
filteredData = [];
if (normalClothingChecked) filteredData = filteredData.concat(furnidata.clothingtypes.clothingitemtypes.furnitype);
if (rareClothingChecked) filteredData = filteredData.concat(furnidata.clothingtypes.rareclothingitemtypes.furnitype);
if (collectibleClothingChecked) filteredData = filteredData.concat(furnidata.clothingtypes.collectibleclothingitemtypes.furnitype);
if (!normalClothingChecked && !rareClothingChecked && !collectibleClothingChecked) filteredData = allFurnis.slice();
}
}

// Filtrar por tipo especial, ambiente, categoría, y colección (si se seleccionaron)
filteredData = filteredData.filter(furni => {
return (
(query === "" || furni.name.toLowerCase().includes(query) || JSON.stringify(furni).toLowerCase().includes(query)) &&
(selectedCategory === "" || (Array.isArray(furni.category)
? furni.category.some(category => category.toLowerCase() === selectedCategory.toLowerCase())
: furni.category.toLowerCase() === selectedCategory.toLowerCase())) &&
(selectedLine === "" || furni.furniline === selectedLine) &&
(selectedEnvironment === "" || furni.environment === selectedEnvironment) &&
(selectedSpecialtype === "" || furni.specialtype === selectedSpecialtype) &&
(!document.getElementById("onShop").checked || furni.offerid !== -1) &&
(selectedFurniType === 'wall' ? furnidata.wallitemtypes.furnitype.some(item => item.id === furni.id) : true) &&
(selectedFurniType === 'floor' ? furnidata.roomitemtypes.furnitype.some(item => item.id === furni.id) : true)
);
});

// Filtrar por "ltdclothing" si está marcado
const ltdclothingChecked = document.getElementById("ltdclothing").checked;
if (ltdclothingChecked) {
filteredData = filteredData.filter(furni => furnidata.ltdclothingitemtypes.furnitype.some(item => item.id === furni.id));
}

// Filtrar específicamente con los inputs de tipo especial, ambiente, categoría, y colección
// Filtrar por tipo especial solo con el objeto JSON "specialtype"
const specialtypeInput = document.getElementById("furniSpecialtypesInput").value.toLowerCase();
if (specialtypeInput) {
filteredData = filteredData.filter(furni => furni.specialtype.toLowerCase().includes(specialtypeInput));
}

// Filtrar por ambiente solo con el objeto JSON "environment"
const environmentInput = document.getElementById("furniEnvironmentsInput").value.toLowerCase();
if (environmentInput) {
filteredData = filteredData.filter(furni =>  furni.environment.toLowerCase().includes(environmentInput));
}

// Filtrar por categoría solo con el objeto JSON "category"
const categoryInput = document.getElementById("furniCategoriesInput").value.toLowerCase();
if (categoryInput) {
filteredData = filteredData.filter(furni => furni.category.toLowerCase().includes(categoryInput));
}

// Filtrar por colección solo con el objeto JSON "furniline"
const lineInput = document.getElementById("furniLinesInput").value.toLowerCase();
if (lineInput) {
filteredData = filteredData.filter(furni => furni.furniline.toLowerCase().includes(lineInput));
}

// Actualizar los datos globales con los resultados filtrados
window.filteredDataGlobal = filteredData;

// Calcular el número de páginas
const totalPages = Math.ceil(filteredData.length / per_page);
if (page > totalPages) {
page = totalPages || 1;
}

// Mostrar los resultados filtrados
mostrarResultados();
}
});
Перед интеграцией функции opulatropdown фильтры в Handlesearch работали, как и ожидалось. Однако, после добавления функциональности заполненного рода , он, по -видимому, мешает результатам поиска. В частности, мне нужно понять, почему взаимодействие с Populatropdown , кажется, нарушает или перезаписывает фильтры в Handlesearch .

Подробнее здесь: https://stackoverflow.com/questions/796 ... ctionality
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»