javascript - 带有 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 = "";
}
}
解决方案
这是一种不同的方法:
首先,我们编写一些执行以下操作的 JS
- 选择页面上的所有 SVG 元素
- 循环遍历这些元素,添加一个“点击”事件监听器
- 使点击事件切换一个
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>
推荐阅读
- three.js - 三色片段着色器
- sql - 删除旧 SQL 中的一行
- ruby-on-rails - Traceback(最近一次调用最后一次):ruby:没有这样的文件或目录——脚本/生成(LoadError)
- bash - 取一个逗号分隔的字符串并将其添加到命令中
- r - 如何在闪亮的可编辑数据表中指定文件名并限制列编辑
- javascript - 错误:当前未启用对实验性语法“可选链”的支持,但已启用
- java - 如何让我的代码继续编码,直到输入“0”
- c++ - 如何生成随机整数数组并提供给另一个文件以对数组执行操作
- javascript - Discord js <@userid> 无法正常工作
- node.js - 如何在一个 Express Router.get 中执行更多查询