繁体   English   中英

JavaScript:单击SVG元素时如何显示警报对话框?

[英]JavaScript: How to make an alert dialog appear when clicking an SVG element?

我在让事件侦听器为我网页上的SVG元素上的click事件工作时遇到麻烦。

现在,每当页面加载时,它将显示第一个对话框( cercle的标题)。 我要它要做的是仅在单击SVG图像的特定SVG元素(或部分)时显示警报消息。 另外,如果再次单击SVG元素,我还将显示什么警报。

请帮忙,因为我对此确实很困惑。

我当前使用的代码是:

const cercle = document.getElementById('leCercle');
const rectangle = document.getElementById("leRect");
const path = document.getElementById("laCourbe");

cercle.addEventListener("click" , showCercleTitle());
path.addEventListener("click" , showPathTitle());
rectangle.addEventListener("click" , showRectTitle());

id和引用是正确的,因为它显示了正确的头衔,但只有一次,为cercle再没有别的。

谢谢!

如果我正确理解了您的问题,则代码的问题是每个事件处理程序之后的() ,然后传递给addEventListener() cercle SVG元素和showCercleTitle()处理程序showCercleTitle()

cercle.addEventListener("click" , showCercleTitle()); //<-- () causing the issue

通过传递showCercleTitle()()我们在调用showCercleTitle它传递给紧接其功能addEventListener()作为click事件处理程序。 这意味着对showCercleTitle()调用结果(可能undefined ?)将用作SVG元素上click事件的处理程序。 要解决此问题,请考虑删除所有事件处理程序分配上的() ,如下所示:

 const cercle = document.getElementById('leCercle'); const rectangle = document.getElementById("leRect"); const path = document.getElementById("laCourbe"); /* Define callback functions for each alert/dialog */ function showCercleTitle() { alert('showCercleTitle') } function showPathTitle() { alert('showPathTitle') } function showRectTitle() { alert('showRectTitle') } /* Add each defined callback as click event listener to respective svg elements. Avoid adding the () after each handler when passing to addEventListener() */ cercle.addEventListener("click", showCercleTitle); path.addEventListener("click", showPathTitle); rectangle.addEventListener("click", showRectTitle); 
 <svg width="200" height="250" version="1.1" xmlns="http://www.w3.org/2000/svg"> <rect id="laCourbe" x="10" y="10" width="30" height="30" stroke="black" fill="transparent" stroke-width="5"/> <rect id="leRect" x="60" y="10" rx="10" ry="10" width="30" height="30" stroke="black" fill="transparent" stroke-width="5"/> <circle id="leCercle" cx="25" cy="75" r="20" stroke="red" fill="transparent" stroke-width="5"/> </svg> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM