基于文本框的Javascript URL重定向 [英] Javascript URL Redirection based on a text box

查看:46
本文介绍了基于文本框的Javascript URL重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我需要根据输入的代码创建一个重定向系统。目前我有:

So, I need to create a redirect system based on a code entered. Currently I have:

<form id="form1" name="form1" method="post" action=""> 
  <pre>     <input type="text" name="meow" id="meow" /> <input type="submit" name="submit" id="submit" value="Submit" onclick="javascript:window.location.href('http://foo.exaple.com/bar/' + document.getElementById("meow").value + '.zip')"/>

基本上,我需要上面的脚本来下载foo.example.com/bar/中的zip文件,基于在文本框中输入的代码喵。

Basically, I need the above script to download a zip file in foo.example.com/bar/, based on a code entered in text box meow.

当我在文本框中输入代码ugh并点击提交时,我想在 http://foo.example.com/bar/ugh.zip

When I enter code "ugh" into text box meow and click submit, I want to download the file at http://foo.example.com/bar/ugh.zip

我该怎么做?

推荐答案

.href 不是函数/方法,它是一个属性,您可以将有效的URI字符串分配给:

.href is not a function/method, it is a property which you assign a valid URI string to:

location.href = 'http://foo.exaple.com/bar/' + document.getElementById('meow').value + '.zip';

参见MDN: window.location 对象

See MDN: window.location Object

附注:如果您不想提交表格,请使用输入 type =button而不是然后提交。

Side-notes: If you don't want to submit the form, use an input type="button" instead of submit then.

在我们的Web 2.0时代,混合结构和行为(HTML和JS)通常是不受欢迎的,所以:

Also mixing structure and behavior (HTML and JS) is usually frowned upon in our Web 2.0 times, so:

<input type="button" name="submit" id="submit" value="Submit">
<script>
document.getElementById('submit').onclick = function() {
    location.href = 'http://foo.exaple.com/bar/' + document.getElementById('meow').value + '.zip';
};
</script>

这也适用于所有浏览器,因为IE6也是如此,你可以省去一些令人头疼的问题,例如在里面混合报价标记。 =]

它也更容易维护,以后您甚至可以将页面的JS移动到单独的 .js 用于缓存和分离结构和行为的文件。

This works nicely in all browsers since IE6 as well and you save some headaches such as mixing up quotes inside the markup. =]
It is also easier to maintain and later you can even move your page's JS into a separate .js file for caching and separation of structure and behavior.

这篇关于基于文本框的Javascript URL重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆