简体   繁体   English

从单击的现有按钮重定向到站点

[英]Redirecting to site from an existing button being clicked

I'm quite new to coding. 我是编码新手。 I have a button with the ID='test'. 我有一个ID ='test'的按钮。 I want to run a line of code in javascript or HTML to redirect users to a site when that button is clicked. 我想在JavaScript或HTML中运行一行代码,以在单击该按钮时将用户重定向到站点。

Button: 按钮:

<button id="test" type="submit" onclick="setNick(document.getElementById('nick').value); return false; return false" class="btn btn-play-guest btn-success btn-needs-server primaryButton" data-itr="play_as_guest">

I tried running this: 我尝试运行此:

<script>
document.getElementById("test").onclick = window.location='http://www.google.com/' 
</script>

However, this would redirect straight away. 但是,这将立即重定向。 I want it to redirect only when the button is clicked. 我希望它仅在单击按钮时才重定向。 Please help me fix this. 请帮我解决这个问题。

Many thanks. 非常感谢。

You are assigning the redirect to the button where you need to assign it to a function. 您正在将重定向分配给需要将其分配给功能的按钮。

You can try something like this: 您可以尝试如下操作:

document.getElementById("test").onclick = function(){ 
     window.location='http://www.google.com/';
}

I would suggest use onclick on button, for example 我建议例如使用onclick on button

your button will look like this 您的按钮将如下所示

<button id="test" onclick="redirect()">Redirect</button>

Now in the script write the redirect function as 现在在脚本中将重定向功能编写为

<script>
  function redirect() {
    window.location.href = "http://www.google.com/";
  }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM