簡體   English   中英

為什么我的 javascript 重定向不起作用“”?

[英]Why does my javascript redirect not work “”?

為什么redirectFunction()函數不重定向到另一個鏈接?

 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>

您需要使用querySelector而不是querySelectorAll querySelectorAll返回一個 dom 元素列表,您不能在這些元素上調用addEventListener方法。

 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>

注意: querySelectorAll總是返回一個數組。 您不能向數組添加事件偵聽器。 循環遍歷節點並在單個節點上添加事件偵聽器。

 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);

因為querySelectorAll返回與查詢匹配的元素數組。 由於您只有一個元素,因此對於該查詢,您需要使用querySelector ,它只選擇一個(第一個)元素。

 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>

這里有一個空格:

你必須刪除它

document.querySelector(".redirectBtn")XXXXXXXXXXXXXXXXXXXXX.addEventListener("click", redirectFunction);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM