JavaScript点击LI元素展示模板时数据不更新及报错问题求助
问题原因及解决办法
核心问题
报错的根本原因是模板元素<template id="template">被意外移除。第一次点击时,你用replaceChild把#info元素整个替换成了模板内容,如果<template>标签原本放在#info容器内部,这会导致模板元素被从DOM中删除,后续点击时document.getElementById('template')返回null,自然无法读取content属性。
另外,replaceChild操作会彻底移除原有的#info元素,后续点击时document.getElementById('info')也会找不到元素,只是这个问题被模板的错误先触发了。
分步解决
调整模板位置
确保<template id="template">标签放在#info容器外部(比如直接放在<body>标签下),这样无论怎么更新#info的内容,模板元素都不会被删除。修改内容更新逻辑
不要替换#info元素本身,而是清空它的内容后再添加新的模板克隆,保留#info容器的存在:// 替换原来的replaceChild代码 const infoDiv = document.getElementById('info'); infoDiv.innerHTML = ''; // 清空原有内容 infoDiv.appendChild(template);优化事件目标判断
原代码中event.target.tagName === 'LI'存在局限性:如果<li>内部有其他子元素(比如<span>、<img>),点击这些子元素时event.target就不是<li>,导致逻辑不触发。改用closest()方法获取最近的<li>父元素:listPokemons.addEventListener('click', event => { const liElement = event.target.closest('LI'); // 获取点击元素的最近LI父元素 if (liElement) { const pokemonId = liElement.dataset.pokemonId; const pokemon = pokemons.find(p => p.id === Number(pokemonId)); // ... 后续逻辑不变 } });
修正后的完整代码
function afficherDetailsPokemon() { const listPokemons = document.getElementById('list-pokemons'); listPokemons.addEventListener('click', event => { const liElement = event.target.closest('LI'); if (liElement) { const pokemonId = liElement.dataset.pokemonId; const pokemon = pokemons.find(p => p.id === Number(pokemonId)); if (pokemon) { // 克隆模板(确保template在#info外部) const template = document.getElementById('template').content.cloneNode(true); // 填充表单值 template.querySelector('#nom_en').value = pokemon.name.english; template.querySelector('#nom_fr').value = pokemon.name.french; template.querySelector('#attaque').value = pokemon.base.Attack; template.querySelector('#defense').value = pokemon.base.Defense; // 添加类型标签 pokemon.type.forEach(type => { const span = document.createElement('span'); span.textContent = type; template.querySelector('#type_p').appendChild(span); }); // 更新#info内容(保留容器本身) const infoDiv = document.getElementById('info'); infoDiv.innerHTML = ''; infoDiv.appendChild(template); } } }); }
内容的提问来源于stack exchange,提问作者Sidepie
相关产品推荐
相关产品推荐

