【问题标题】:Javascript button and document.locationJavascript 按钮和 document.location
【发布时间】:2012-06-20 03:27:15
【问题描述】:

我正在尝试用 javascript 做一些事情(我是初学者,我正在研究它),我想知道如何打开保存在变量中的链接。我正在尝试...

<input type="button" onclick="document.location.href=Query;" />

Query 是 Ricerca 方法中的一个变量,可与另一个按钮一起使用

function ricerca()
        {
            var Link = "http://www.mysite.com/search?q=variabile&k=&e=1";

            var Name= document.getElementById('utente').value;

            var Query = Link.replace("variabile",Name);

            alert(Query); 
            return false;
        } 

另一个按钮生成自定义搜索链接...

input type="text" id="utente">
<input type="submit" value="Click me" onclick="return ricerca();" /> 

我的代码有什么问题?

【问题讨论】:

    标签: javascript html url hyperlink


    【解决方案1】:

    这个标记:

    <input type="button" onclick="document.location.href=Query;" />
    

    ...需要您有一个名为Query全局 变量,而您没有该变量。您在函数中有一个局部变量。您需要有一个函数(可能是您的ricerca 函数?)返回 URL,然后调用该函数。像这样的:

    function ricerca()
    {
        var Link = "http://www.mysite.com/search?q=variabile&k=&e=1";
    
        var Name= document.getElementById('utente').value;
    
        var Query = Link.replace("variabile",Name);
    
        return Query;
    } 
    

    <input type="button" onclick="document.location.href=ricerca();" />
    

    另外,只需使用location.href 而不是document.location.hreflocation 是一个全局变量(它是window 的一个属性,所有window 属性都是全局变量),这就是你用来加载新页面的变量。

    【讨论】:

    • 非常感谢!这是对我有帮助的独特答案!我不知道javascript中的变量不是全局的。
    • @user1453638:很高兴有帮助!因为你是新来的,所以我会指给你看这个:meta.stackexchange.com/questions/5234/…
    • @T.J.Crowder 最后一个问题,设置location 不是比location.href 更好吗?据我记得,location.href 在某些(较旧的)浏览器中是只读的,在处理像这样的重定向时,我通过将 location.href 更改为 location 解决了许多问题。
    • @FabrícioMatté:恐怕我不知道。我几乎从来没有这样做过,老实说,我不记得在极少数情况下我是否设置了locationlocation.href。 :-)
    • 哦,我发现了一个相关问题也得到了正确回答:stackoverflow.com/a/275102/1331430:)
    猜你喜欢
    • 1970-01-01
    • 2013-12-27
    • 2013-02-11
    • 2011-01-26
    相关资源
    最近更新 更多