如何将javascript值传递给html href属性?

时间:2017-12-21 18:58:49

标签: javascript html

我想在html体内的href属性中传递finalName的值。我怎么能这样做?

<html>
<script type="text/javascript" language="Javascript">
        var url = window.location.search;
        var val = getParameter('n');
        var finalName = "";
        if( val == false ) {
            var a= prompt("Enter your name & see the magic", "");
            if(a){
                window.location.href = '?n='+a;
                document.getElementById("demo2").innerHTML = a ;
                finalName = a;
            }
        }
        else {
            document.getElementById('demo2').innerHTML = val;
        }
</script>

<body>
<a class="footerbtn" href="whatsapp://send?text= send you special surprise message%0A%0ATouch this blue line %0Aenter your name %0A http://magic.pagalworld.buzz/?n=" 
  onclick="location.href=this.href+finalName;return false;"><img width="25px" height="25px" src="wp.png"/><b style="font-size: 15px;"> Click Here to Share on Whatsapp</b> <img width="25px" height="25px" src="wp.png"/></a>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您可以使用window.finalName使变量可访问。 例如:

&#13;
&#13;
<script type="text/javascript" language="Javascript">
        var url = window.location.search;
        var val = getParameter('n');
        window.finalName = "";
        if( val == false ) {
            var a= prompt("Enter your name & see the magic", "");
            if(a){
                window.location.href = '?n='+a;
                document.getElementById("demo2").innerHTML = a ;
                window.finalName = a;
            }
        }
        else {
            document.getElementById('demo2').innerHTML = val;
        }
</script>
&#13;
<html>


<body>
<a class="footerbtn" href="whatsapp://send?text= send you special surprise message%0A%0ATouch this blue line %0Aenter your name %0A http://magic.pagalworld.buzz/?n=" 
  onclick="location.href=this.href+finalName;return false;"><img width="25px" height="25px" src="wp.png"/><b style="font-size: 15px;"> Click Here to Share on Whatsapp</b> <img width="25px" height="25px" src="wp.png"/></a>
</body>
</html>
&#13;
&#13;
&#13;