通过JavaScript动态更改网页的meta标签内容

6
我想使用Javascript动态更改meta标签的内容,如刷新率和网址。使用按钮启用Javascript函数。尝试了3种方法,但都无效。请帮忙解决。
谢谢,Amresh
<!DOCTYPE html>
<html>
<head>
<meta HTTP-EQUIV="refresh" name="description" id="mymetatag"
      content="5;URL=http://localhost:6985/ChartJSDemo/Is_Mainpage.html">
<meta charset="ISO-8859-1">

<title>Processing Details</title>
<link rel="stylesheet" type="text/css" href="css/MF_job_failTable.css">
</head>

<body>

<button onclick="myFunction()">Click me</button>

<script>
function myFunction() {
    <!--document.querySelector('meta[name="description"]').setAttribute("content","5;URL=http://google.co.in");-->
    <!--document.getElementById("mymetatag").setAttribute("content", "5;URL=http://google.co.in");-->

  var m = document.createElement('meta'); 
  m.name = 'description'; 
  m.id = 'mymetatag';
  m.content = '5;URL=http://google.co.in'; 
  m.HTTP-EQUIV= 'refresh';
  document.head.appendChild(m);
}
</script>
2个回答

3

这对我起作用。 问题可能是您尝试了一个不起作用的第一段代码,并且您使用HTML注释<!-- [...] -->而不是Javascript注释:// [...]/** [...] */

<!DOCTYPE html>
<html>

<head>
  <meta HTTP-EQUIV="refresh" name="description" id="mymetatag" content="5;URL=http://localhost:6985/ChartJSDemo/Is_Mainpage.html">
  <meta charset="ISO-8859-1">

  <title>Processing Details</title>
  <link rel="stylesheet" type="text/css" href="css/MF_job_failTable.css">
</head>

<body>

  <button onclick="myFunction()">Click me</button>

  <script>
    function myFunction() {
      document.getElementById("mymetatag").setAttribute("content", "5;URL=http://google.co.in");
    }
  </script>
</body>
</html>


是的,这在网络浏览器中可以运行。我尝试在Eclipse Tomcat服务器上运行,但它没有工作。谢谢兄弟。 - Amresh

0

看起来你误用了元标签的功能,JS不能在请求之间保存状态。而且,顺便说一下,你可以使用JavaScript自身进行重新加载/重定向。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接