getElementById из кнопки внутри списка innerHTML

#javascript #html #gis #arcgis-js-api

#javascript #HTML #гис #arcgis-js-api

Вопрос:

Мне нужно сбросить введенную пользователем переменную, которая находится внутри списка innerHTML, который вызывается функцией expand из API JavaScript esri.

введите описание изображения здесь

Этот код создает виджет расширения

 // Displays instructions to the user for understanding the sample
// And places them in an Expand widget instance
const sampleInstructions = document.createElement('div');
sampleInstructions.style.padding = '10px';
sampleInstructions.style.backgroundColor = 'rgba(12, 32, 116, 0.6)';
sampleInstructions.style.color = '#dbdbdb';
sampleInstructions.style.fontFamily = 'Arial, Helvetica, sans-serif';
sampleInstructions.style.width = '450px';
sampleInstructions.innerHTML = [
    '<div class="instruct">',
    'Use the input below to designate the buffer distance (in miles) to aggregate all variables (in right side panel).<br><br>',
    '</div>',
    '<div class="inputDiv">',
    '<label for="userInput" class="userInputLabel">Set Buffer Radius (miles) for Aggregation</label>',
    '<input type="number" id="input-number" class="radiusInput" placeholder="Radius" min="0" step="0.5"></input>',
    '<button type="button" id= clear> Click here to clear </button>',

    '</div>'
].join(' ');
  

Этот код работает, если у меня есть кнопка, которой нет в виджете:

 var ele = document.getElementById('clear')
ele.addEventListener('click', clearGeometry);


// Clear the geometry and set the default renderer
function clearGeometry() {
    clearCharts();
    document.getElementById('input-number').value = ''
    if (highlightHandle) {
        highlightHandle.remove();
        highlightHandle = null;
    }
}
  

Этот код добавляет виджет в веб-приложение

 const instructionsExpand = new Expand({
    expandIconClass: 'esri-icon-description',
    expandTooltip: 'Set Aggregate Buffer',
    view: view,
    content: sampleInstructions,
    expanded: view.widthBreakpoint !== 'xsmall'
});
  

Ответ №1:

Проблема может заключаться в том, что виджет расширения динамически загружает элементы html, которые не загружаются в DOM при загрузке страницы. Следовательно, вы должны привязать событие щелчка ко всему документу, а не к этой конкретной кнопке очистки.

 document.addEventListener("click", event => {
    if(event.target.id == 'clear') clearGeometry();
});

// Clear the geometry and set the default renderer
function clearGeometry() {
    clearCharts();
    document.getElementById('input-number').value = ''
    if (highlightHandle) {
        highlightHandle.remove();
        highlightHandle = null;
    }
}