javascript - 从 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'
});
解决方案
问题可能是 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;
}
}
推荐阅读
- git - 修复提交后 git 如何处理 squash 提交?
- arrays - 如何使用 scala 过滤火花的数据帧数组
- node.js - 上传到火力基地
- typescript - 将参数传递到打字稿中是如何工作的?
- react-native - 更新 react-native-maps 以使用 create-react-native-app
- ios - 将日期添加到字符串日期 swift
- c++ - 如何找出 Kernel32 依赖项的来源
- android-activity - 无法从 Android App 中的菜单打开的子活动返回父活动
- php - 在 iOS 聊天应用中刷新聊天消息
- c# - 将实体框架 C# 代码转换为原始 SQL 以提高性能