I am writing a small practice website. Relevant HTML:
...
<body>
<div id="button">CLICK ME</div>
<script src="assets/js/app.js"></script>
</body>
...
My app.js file has the following code:
document.querySelector("#button").addEventListener("click", new function() {
alert("test");
});
When I reload the page, the event triggers. After that, clicking the div
does nothing. What is causing this issue and how can I fix it?
insead of new function() use only function
document.querySelector("#button").addEventListener("click", function() {
alert("test");
});
The second parameter of addEventListener
takes a reference to a function. Putting new
in front, you create a new object and you apply an anonymous function as constructor. So the return value of it is an object instead of a function, which is what you need.
As such, your code would need to be (as pointed out by Met Byrdy):
document.querySelector("#button").addEventListener("click", function() {
alert("test");
});
Just for fun though, I will give you a way to actually use new
in that context. You can use the new Function
syntax to do it:
document.querySelector("#button").addEventListener("click", new Function("alert('dsds')"));
Not that I recommend it, but thought you should know there is a way to write a function like that as well.
Reference: https://javascript.info/new-function
addEventListener takes two arguments, the second argument is the function that you want the listener to invoke every time the event is triggered, in your case "click" event.
When you put "new" in front of the function it changes the function into a constructor function that creates a class instance ( returns an object ). That is why you need to use the function without the new keyword just like below.
document.querySelector("#button").addEventListener("click", function() {
alert("test");
});
-- Edit --
You can check this stackoverflow issue
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.