javascript 按钮 onclick 未重定向到正确的 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18857545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:27:32  来源:igfitidea点击:

Button onclick not redirecting to correct URL

javascript

提问by Megan Taylor

<button id="promoCodeSubmit" onclick="window.location.href='http://www.test.com'+document.getElementById('promoCodeValue').value;">Apply</button>

<button id="promoCodeSubmit" onclick="window.location.href='http://www.test.com'+document.getElementById('promoCodeValue').value;">Apply</button>

Trying to use the code above to redirect a page. console.log is printing out the correct URL, but page gets redirected incorrectly. Any ideas why?

尝试使用上面的代码重定向页面。console.log 打印出正确的 URL,但页面被错误地重定向。任何想法为什么?

回答by Sachin

Why don't simplify your code and make it readable.It will also solve your problem. HTML

为什么不简化您的代码并使其具有可读性。它也将解决您的问题。HTML

<button id="promoCodeSubmit" onclick="RedirectToLocation()">Apply</button>

<input id="promoCodeValue" type="text" value="testing123" />

Script:

脚本:

function RedirectToLocation(){
 window.location.href='http://www.test.com'+document.getElementById('promoCodeValue').value;
}

Js Fiddle Demo

Js小提琴演示

回答by abc123

Demo jsFiddle

演示 jsFiddle

The following works fine for me, let me know if you need more.

以下对我来说很好用,如果您需要更多,请告诉我。

HTML

HTML

<button id="promoCodeSubmit" onclick="ClickEvent()">Apply</button>
<input type="hidden" id="promoCodeValue" value="1"/>

JS

JS

function ClickEvent(){
    window.location.href='http://www.test.com'+document.getElementById('promoCodeValue').value;
}