Javascript按钮和document.location

use*_*638 1 html javascript url hyperlink

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

<input type="button" onclick="document.location.href=Query;" />
Run Code Online (Sandbox Code Playgroud)

其中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;
        } 
Run Code Online (Sandbox Code Playgroud)

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

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

我的代码出了什么问题?

T.J*_*der 5

这个标记:

<input type="button" onclick="document.location.href=Query;" />
Run Code Online (Sandbox Code Playgroud)

...需要你有一个你没有的全局变量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;
} 
Run Code Online (Sandbox Code Playgroud)

<input type="button" onclick="document.location.href=ricerca();" />
Run Code Online (Sandbox Code Playgroud)

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