SVG - click is not a function

前端 未结 2 1209
故里飘歌
故里飘歌 2020-12-21 01:32

I have an element like this.



        
相关标签:
2条回答
  • 2020-12-21 02:02

    click() is a function that's only defined on HTML elements. Fortunately it's a convenience function and we can implement it ourselves pretty easily i.e.

    document.getElementById('box_w').dispatchEvent(new Event('click'));
    

    That's all the click() function does underneath the hood anyway.

    Here's an example:

    document.getElementById('box_w').dispatchEvent(new Event('click'));
    <g id="box_w" onclick="alert('hi')"> 
        <rect fill="#FFFFFF" height="68.522" stroke="#FFFFFF" stroke-miterlimit="10" width="119.297" x="306.673" y="384.406"></rect> 
    </g>

    0 讨论(0)
  • 2020-12-21 02:06

    Try to use onclick instead of click.

    document.querySelector("g#box_w").onclick();
    

    Remember that what we are doing here is calling the interface of the shape. So onclick needs to be defined in svg as it is in the question:

    <g id="box_w" onclick="recordResponseKeyboard('W');"></g>
    
    0 讨论(0)
提交回复
热议问题