首页 > 解决方案 > 从 innerHTML 列表中的按钮获取元素ById

问题描述

我需要重置用户输入的变量,该变量位于由 esri JavaScript API 的扩展函数调用的 innerHTML 列表中。

在此处输入图像描述

此代码正在构建扩展小部件

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

此代码将小部件添加到 Web 应用程序

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

标签: javascripthtmlgisarcgis-js-api

解决方案


问题可能是 Expand 小部件在页面加载时动态加载未在 DOM 中加载的 html 元素。因此,您必须将 click 事件绑定到整个文档,而不是那个特定的清除按钮。

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

推荐阅读