如何使用php中的onclick事件重定向页面?

Har*_*ana 5 html php

我尝试使用此代码,但它不起作用,

<input type="button" value="Home" class="homebutton" id="btnHome" onClick="<?php header("Location: /index.php"); ?>" />
Run Code Online (Sandbox Code Playgroud)

m59*_*m59 15

你不能使用PHP代码客户端.你需要使用javascript.

<input type="button" value="Home" class="homebutton" id="btnHome" 
onClick="document.location.href='some/page'" />
Run Code Online (Sandbox Code Playgroud)

但是,你真的不应该使用内联js(如onclick here).有关此问题的研究:https://www.google.com/search?q = Why +is + inline+js+bad%3F

这是一个干净的方式:现场演示(点击).

标记:

<button id="myBtn">Redirect</button>
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

var btn = document.getElementById('myBtn');
btn.addEventListener('click', function() {
  document.location.href = 'some/page';
});
Run Code Online (Sandbox Code Playgroud)

如果你需要用php写入位置:

  <button id="myBtn">Redirect</button>
  <script>
    var btn = document.getElementById('myBtn');
    btn.addEventListener('click', function() {
      document.location.href = '<?php echo $page; ?>';
    });
  </script>
Run Code Online (Sandbox Code Playgroud)