如何实现点击图片将其src值填充至hidden字段menu?
先排查核心问题点
你的函数逻辑本身没问题,无法填充值大概率是外部因素导致,按以下步骤排查:
- 确认hidden元素ID正确性:检查页面中是否存在
<input type="hidden" id="menu" name="menu">,ID拼写、大小写必须完全匹配,且不能有重复ID的元素。 - 检查onclick参数传递:确保图片的点击事件是
onclick="myFunction(this)",必须传递this,否则函数里的imgs无法指向当前点击的图片。 - 调试验证值的获取:在函数中加入
console.log(imgSRC)和console.log(document.getElementById("menu")),查看是否正确获取到图片src,以及hidden元素是否存在。
修正后的基础实现代码
确保HTML结构正确:
<!-- 菜单图片,传递this到点击函数 --> <img src="menu-item1.jpg" alt="招牌汉堡" onclick="myFunction(this)"> <img src="menu-item2.jpg" alt="芝士薯条" onclick="myFunction(this)"> <!-- 图片预览区域 --> <div style="display: none;"> <img id="expandedImg" src="" alt="预览图"> <div id="imgtext"></div> </div> <!-- 表单hidden字段 --> <input type="hidden" id="menu" name="menu">
优化后的JS函数(增加安全判断和预览图设置):
function myFunction(imgs) { const expandImg = document.getElementById("expandedImg"); const imgText = document.getElementById("imgtext"); const imgSRC = imgs.src; // 用textContent替代innerHTML,避免XSS风险 imgText.textContent = imgs.alt; expandImg.parentElement.style.display = "block"; // 同步设置预览图的src,提升用户体验 expandImg.src = imgSRC; const menuInput = document.getElementById("menu"); if (menuInput) { menuInput.value = imgSRC; } else { console.error("未找到id为menu的hidden输入框"); } }
更优的事件委托实现方案
如果菜单图片较多,不建议给每个图片单独绑定onclick,用事件委托更高效:
// 页面加载完成后绑定事件 document.addEventListener('DOMContentLoaded', function() { // 选择菜单图片的父容器(根据实际HTML结构调整选择器) const menuContainer = document.querySelector('.menu-images'); const expandImg = document.getElementById("expandedImg"); const imgText = document.getElementById("imgtext"); const menuInput = document.getElementById("menu"); menuContainer.addEventListener('click', function(e) { // 只处理图片元素的点击 if (e.target.tagName === 'IMG') { const currentImg = e.target; const imgSRC = currentImg.src; imgText.textContent = currentImg.alt; expandImg.parentElement.style.display = "block"; expandImg.src = imgSRC; if (menuInput) { menuInput.value = imgSRC; } } }); });
对应的HTML结构(无需每个图片加onclick):
<div class="menu-images"> <img src="menu-item1.jpg" alt="招牌汉堡"> <img src="menu-item2.jpg" alt="芝士薯条"> <img src="menu-item3.jpg" alt="冰爽可乐"> </div>
内容的提问来源于stack exchange,提问作者Miles Baron
相关产品推荐
相关产品推荐

