Why doesn't the redirectFunction()
function redirect to another link?
document.querySelectorAll(".redirectBtn") .addEventListener("click", redirectFunction); function redirectFunction() { window.location.href = ("https://stackoverflow.com/questions/29475323/call-function-with-classname-onclick-js/29475365"); }
<h1>Redirect to a Webpage Example</h1> <button class="redirectBtn">Redirect</button> <h2>Click the above button to Redirect to another Webpage</h2>
You need to use querySelector
instead of querySelectorAll
. querySelectorAll returns a list of dom elements on which you can't invoke the addEventListener
method.
document.querySelector(".redirectBtn") .addEventListener("click", redirectFunction); function redirectFunction() { window.location.href = ("https://stackoverflow.com/questions/29475323/call-function-with-classname-onclick-js/29475365"); }
<h1>Redirect to a Webpage Example</h1> <button class="redirectBtn">Redirect</button> <h2>Click the above button to Redirect to another Webpage</h2>
Note: querySelectorAll
always return an array. You cannot add event listener to an array. Loop through the nodes and add event listener on individual node.
document.querySelectorAll(".redirectBtn").forEach((node) => node.addEventListener("click", redirectFunction)) function redirectFunction() { window.location.href = ("https://stackoverflow.com/questions/29475323/call-function-with-classname-onclick-js/29475365"); }
<h1>Redirect to a Webpage Example</h1> <button class="redirectBtn">Redirect</button> <h2>Click the above button to Redirect to another Webpage</h2>
querySelectorAll
返回一个节点集合,您必须使用循环添加eventListener
或者您可以像这样使用querySelector
document.querySelector(".redirectBtn").addEventListener("click", redirectFunction);
Because querySelectorAll
returns an array of elements that matches the query. Since you only have one element, with that query, you need to use querySelector
, which only selects one (1st) element.
document.querySelector(".redirectBtn") .addEventListener("click", redirectFunction); function redirectFunction() { window.location.href = ("https://stackoverflow.com/questions/29475323/call-function-with-classname-onclick-js/29475365"); }
<h1>Redirect to a Webpage Example</h1> <button class="redirectBtn">Redirect</button> <h2>Click the above button to Redirect to another Webpage</h2>
there is a space here:
you have to remove it
document.querySelector(".redirectBtn")XXXXXXXXXXXXXXXXXXXXX.addEventListener("click", redirectFunction);
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.