访问Javascript变量

时间:2015-03-24 12:45:29

标签: javascript html

我有以下代码:

  <script>
    var url = document.URL;
    var mypage = /page=([0-9]*)/;
    var match = mypage.exec(url);
    if (match == null) {
      var next = url + "&page=2";
      var before = null;
    } else {
      var nextpage = parseInt(match[1]) + 1;
      var lastpage = parseInt(match[1]) - 1;
      res1 = url.replace(/page=[0-9]*/g, "page=" + nextpage);
      res2 = url.replace(/page=[0-9]*/g, "page=" + lastpage);
    }
  </script>
  <div class="mainbar"><div class="txt-vertical-align">something</div><a href=<%= res1 %> >link text</a></div>

我的目标是创建一个超链接,url存储在变量res1中。但是,我发布的代码不起作用......

2 个答案:

答案 0 :(得分:0)

尝试此操作...构建res1变量后,只需使用js

将其分配给a href属性

已编辑在脚本声明之前输入html。

<div class="mainbar"><div class="txt-vertical-align">something</div><a href="#" id="MyLink" >link text</a></div>

<script>
 var url = document.URL;
 var mypage = /page=([0-9]*)/;
 var match = mypage.exec(url);
 if (match == null) {
   var next = url + "&page=2";
   var before = null;
 } else {
   var nextpage = parseInt(match[1]) + 1;
   var lastpage = parseInt(match[1]) - 1;
   res1 = url.replace(/page=[0-9]*/g, "page=" + nextpage);
   res2 = url.replace(/page=[0-9]*/g, "page=" + lastpage);

  //new code that sets href property
  document.getElementById("MyLink").href= res1; 

}
</script>

答案 1 :(得分:0)

据我所知,没有弯曲javascript变量的功能,例如&lt;%= res1%&gt;

但我很高兴您研究DOM API,您可以访问和操作HTML文档的元素和节点的属性。
https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model

<a id='a-demo' href=<%= res1 %> >link text</a>
<script>
//This script should be after a tag
var url = "path";
document.getElementById("a-demo").href = url;
</script>

随意发表评论。