javascript - 如何用 PHP echo 做 JS 函数?
问题描述
我正在尝试为从数据库回显的一组值创建一个弹出菜单。单击 svg 时,需要显示与 echo 中的 svg 对应的弹出菜单。除了到目前为止,它只适用于第一个被回显的。如何修复它以显示与正确 svg 对应的弹出窗口。这是我目前得到的:
PHP/HTML:
echo('
<svg class="option-3" width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M9 10.5C9.82843 10.5 10.5 9.82843 10.5 9C10.5 8.17157 9.82843 7.5 9 7.5C8.17157 7.5 7.5 8.17157 7.5 9C7.5 9.82843 8.17157 10.5 9 10.5Z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M15 10.5C15.8284 10.5 16.5 9.82843 16.5 9C16.5 8.17157 15.8284 7.5 15 7.5C14.1716 7.5 13.5 8.17157 13.5 9C13.5 9.82843 14.1716 10.5 15 10.5Z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M3 10.5C3.82843 10.5 4.5 9.82843 4.5 9C4.5 8.17157 3.82843 7.5 3 7.5C2.17157 7.5 1.5 8.17157 1.5 9C1.5 9.82843 2.17157 10.5 3 10.5Z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
<div class="menu-option-popout"></div>
');
JS:
document.querySelector(".option-3").addEventListener("click", function(){
document.querySelector(".menu-option-popout").style.display = "block";
});
解决方案
如果每个弹出窗口<div>
立即出现在其相应的<svg>
标签之后(如您的示例中所示),您可以利用该.nextElementSibling
属性来获取单击<div>
的后面的<svg>
。
在您的 HTML 结尾处:
<script>
// Add an event listener to each .option-3 element:
document.querySelectorAll('.option-3').forEach(item => {
item.addEventListener('click', event => {
let popout = event.target.nextElementSibling; // This element's next element (a .menu-option-popout)
popout.style.display = 'block'; // Show the popout
})
})
</script>
推荐阅读
- mysql - 使用字符串类型主键时无法创建数据库
- angular - 具有本地存储和远程同步的 Ionic5 提供程序
- vue.js - 如何在运行在 tomcat 上的 Vue App 中添加安全标头
- typescript - TypeScript 可传递地导入 ES 库
- excel - 将多列列表框移回 Excel
- java - 一对多 SQL 关系
- postgresql-9.6 - Postgres COPY FROM 是否应该更新 BRIN 索引?
- excel - 连接时如何将变体暗淡传递给字符串?
- ios - Realm Swift:对象已被删除或失效
- python - 如何添加 foriegnkey 对象并通过 Django rest Framework 中的单个端点将其连接为 post 对象