简体   繁体   中英

Redirecting to site from an existing button being clicked

I'm quite new to coding. I have a button with the 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.

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

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>

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.

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