首页 > 解决方案 > 带有 PHP mysqli_fetch_assoc 回显的 JS 函数

问题描述

我有一个 PHP 回显,在其中显示带有 mysqli_fetch_assoc 和回显的选择查询的结果 * 只有回显的一部分在 *. 但我希望切换页面功能在单击其中一个具有切换 id 的 svg 时运行。但是,因为我正在回显结果数组,所以只有结果的第一个回显有效,其余的则无效,因为 id 都是相同的。我该怎么做才能使该函数适用于每个结果回显。谢谢

HTML/PHP:

echo'
    <svg id="toggle" onclick="togglepage()" class="hover-box-menu2 toggle-page" width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M7.5 15L12.5 10L7.5 5" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
    </svg>
    ';

JS:

function togglepage() {
    if (document.getElementById("toggle").style.transform == "rotate(0deg)" || document.getElementById("toggle").style.transform == "") {
        document.getElementById("toggle").style.transform = "rotate(90deg)";
    }
    else if (document.getElementById("toggle").style.transform == "rotate(90deg)") {
        document.getElementById("toggle").style.transform = "";
    }
}

标签: javascriptphphtml

解决方案


这是一种不同的方法:

首先,我们编写一些执行以下操作的 JS

  1. 选择页面上的所有 SVG 元素
  2. 循环遍历这些元素,添加一个“点击”事件监听器
  3. 使点击事件切换一个rotate

然后我们创建一个 css 类.rotate并为其添加 transform 属性。

现在,当您单击 SVG 时,它将在 90 度和 0 度之间旋转。

document.querySelectorAll('.rotateable').forEach(el => {
  el.addEventListener('click', () => {
    el.classList.toggle('rotate')
  })
})
.rotate {
  transform: rotate(90deg);
  /* more styles here */
}
<svg class="rotateable hover-box-menu2" width="40" height="40" viewBox="0 0 20 20" fill="black" xmlns="http://www.w3.org/2000/svg">
  <path d="M7.5 15L12.5 10L7.5 5" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
<svg class="rotateable hover-box-menu2" width="40" height="40" viewBox="0 0 20 20" fill="black" xmlns="http://www.w3.org/2000/svg">
  <path d="M7.5 15L12.5 10L7.5 5" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
<svg class="rotateable hover-box-menu2" width="40" height="40" viewBox="0 0 20 20" fill="black" xmlns="http://www.w3.org/2000/svg">
  <path d="M7.5 15L12.5 10L7.5 5" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>


推荐阅读