将Javascript变量传递给<a href=""></a>

时间:2009-06-10 11:32:13

标签: javascript

<script language="javascript" type="text/javascript">
var scrt_var = 10; 
</script>

HTML部分:

<html>
 this is a <a href ="2.html & Key= scrt_var">Link  </a>
</html>

我只想将javascript变量发送到link(url参数)

没有AJAX

8 个答案:

答案 0 :(得分:52)

如果您希望它是动态的,那么使用点击时变量的值,请执行以下操作:

<script language="javascript" type="text/javascript">
var scrt_var = 10; 
</script>
<a href="2.html" onclick="location.href=this.href+'?key='+scrt_var;return false;">Link</a>

当然,这是快速而肮脏的解决方案。你应该有一个脚本,在DOM加载后为所有相关的<a>元素添加一个onclick处理程序。

答案 1 :(得分:16)

将id属性放在锚元素

<a id="link2">

在页面加载事件上设置href属性:

(function() {
    var scrt_var = 10;
    var strLink = "2.html&Key=" + scrt_var;
    document.getElementById("link2").setAttribute("href",strLink);
})();

答案 2 :(得分:10)

<script>
   var scrt_var = 10;
   document.getElementById("link").setAttribute("href",scrt_var);
</script>
<a id="link">this is a link</a>

答案 3 :(得分:8)

或者你可以使用document.write:

...HTML
<script type="text\javascript">
var location = "http://";
document.write('<a href="' + location + '">Link text</a>');
</script>
...the rest

答案 4 :(得分:7)

<html>

<script language="javascript" type="text/javascript">
var scrt_var = 10; 
openPage = function() {
location.href = "2.html?Key="+scrt_var;
}
</script>

 this is a <a href ="javascript:openPage()">Link  </a>
</html>

答案 5 :(得分:0)

如果您使用国际化(i18n),并且在切换到其他语言后,可能会在网址末尾添加?locale=fr?fr之类的内容。但是当你转到点击事件的另一个页面时,翻译开关将不稳定。

对于这种情况,必须生成DOM单击事件处理函数,以通过将开关状态存储为变量来处理所有a.href属性,并将其添加到所有a标记的尾部。

答案 6 :(得分:0)

您还可以使用快速框架

app.get("/:id",function(req,res)
{
  var id = req.params.id;
  res.render("home.ejs",{identity : id});
});

Express文件,该文件从node.js接收JS变量标识

<a href = "/any_route/<%=identity%>包含标识JS变量到您的href中,输入很方便

答案 7 :(得分:0)

JAVASCRIPT代码:

<script>

    function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

var user = getUrlVars()["user"];
var pass = getUrlVars()["pass"];
var sub  = getUrlVars()["sub"];
</script>

<script>
    var myApp = angular.module('myApp',[]);

myApp.controller('dropdownCtrl', ['$scope','$window','$http', function($scope, $window, $http) {

 $http.get('http://dummy.com/app/chapter.php?user='+user+'&pass='+pass)

     .then(function (response) {$scope.names = response.data.admin;});
    $scope.names = [];

        $http.get('http://dummy.com/app/chapter.php?user='+user+'&pass='+pass+'&sub='+sub)

            .then(function (response) {$scope.chapter = response.data.chp;});
           $scope.chapter = [];

};


}]);
    </script>

HTML:

<div ng-controller="dropdownCtrl">
<div ng-repeat="a in chapter">
<a href="topic.html?ch={{a.chapter}}" onClick="location.href=this.href+'&user='+user+'&pass='+pass+'&sub='+sub;return false;">{{a.chapter}}</a>
</div>