0

Does this code work for anyone else. For the longest time adding an event listener hasn't worked.

<head>
    <title>Page Title</title>
    <script>
    window.onload = init();

    function init() {
        svg = document.getElementsByTagName('svg');
        svg[0].addEventListener('click', mouseClick, false);
    }

    function mouseClick() {
        alert('mouseClicked');
    }
    </script>
</head>
<body>

<svg><rect x="100" y="100" width="200" height="75"/></svg>

</body>

For every project I've worked on, I've had to use an alternative method. Am I doing something wrong with "addEventListener"? Or what?

4

2 回答 2

1

init() calls the function and unless it returns a function, this will not work. What you need to do is pass the function, not the return value thereof:

window.onload = init;
于 2013-07-12T21:26:50.733 回答
1

Your problem is:

window.onload = init();

By including the brackets, you're calling the function at that point, so what you're doing is assigning the result of a call to init to window.onload. You need:

window.onload = init;

which will assign the function init to window.onload.

于 2013-07-12T21:27:35.140 回答