首页 > 解决方案 > 如何用 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";
});

标签: javascriptphphtml

解决方案


如果每个弹出窗口<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>

推荐阅读