生成和使用URL作为jscript变量

时间:2013-02-25 19:28:48

标签: html url javascript-events url-rewriting createelement

我现在花了几个小时试图通过阅读其他帖子来弄清楚你是如何做到这一点的 - 我甚至有一个工作的jsfiddle,但是无法在我的页面中使用它。

我想构建一个多次在页面上使用的URL,这样当我需要更新URL时,我只需要通过标题中的javascript变量在一个地方进行。

我将网址分为两部分,因为其中一个变量几乎总是相同,但另一个变量在不同的网页上最常见。

例如,我在我的标题中声明:

<script language="javascript" type=”text/javascript”>
function goSchedule()
{
var schedulePath = "http://[rootPath]/";
var scheduleFileName = "[extension to document].htm";
schedulePath = schedulePath + scheduleFileName;
document.getElementById('go').href= schedulePath;
}
</script>

然后我似乎无法弄清楚如何在href中调用它。这不起作用:

<p>Click the following link to test:<a href="javascript:goSchedule();" id="go">Test this link</a></p>

如果您回答,请说明如何创建初始javascript 如何正确调用它,使其成为活动网址。

1 个答案:

答案 0 :(得分:0)

看起来您正在尝试在用户单击链接时替换href属性。我建议您在页面加载完成后立即为所有链接替换href属性。

确保在头部

中声明您的功能
<head>

<!-- Other head declarations ... -->

<script language="javascript" type=”text/javascript”>
function goSchedule() {
    var schedulePath = "http://[rootPath]/";
    var scheduleFileName = "[extension to document].htm";
    schedulePath = schedulePath + scheduleFileName;
    document.getElementById('go').href = schedulePath;
}
</script>
</head>

然后将此方法绑定到body元素的onload事件,如此

<body onload="goSchedule()">

    <!-- Other HTML Stuff Goes Here ... -->

    <p>Click the following link to test:<a href="javascript:void" id="go">Test this link</a>
    </p>
</body>

这是完整的html页面:

<html>
    <head>

        <!-- Other head declarations ... -->

        <script language="javascript" type="text/javascript">
            function goSchedule() {
                var schedulePath = "http://support.mozilla.org/";
                var scheduleFileName = "en-US/products/firefox?as=u&utm_source=inproduct";
                schedulePath = schedulePath + scheduleFileName;
                document.getElementById('go').href = schedulePath;
            }
        </script>
    </head>
    <body onload="goSchedule()">

        <!-- Other HTML Stuff Goes Here ... -->

        <p>Click the following link to test:<a href="javascript:void" id="go">Test this link</a>
        </p>
    </body>
</html>