Kaz*_*lfe 1 javascript javascript-events
所以,我需要根据输入的代码创建一个重定向系统。目前我有:
<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')"/>
Run Code Online (Sandbox Code Playgroud)
基本上,我需要上面的脚本根据在文本框喵喵中输入的代码在 foo.example.com/bar/ 中下载 zip 文件。
当我在文本框中输入代码“ugh”并单击提交时,我想在http://foo.example.com/bar/ugh.zip下载文件
我怎样才能做到这一点?
.href 不是函数/方法,它是一个属性,您可以将有效的 URI 字符串分配给:
location.href = 'http://foo.exaple.com/bar/' + document.getElementById('meow').value + '.zip';
Run Code Online (Sandbox Code Playgroud)
见 MDN:window.location对象
旁注:如果您不想提交表单,请使用输入type="button"而不是提交。
在我们的 Web 2.0 时代,混合结构和行为(HTML 和 JS)通常是不受欢迎的,所以:
<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>
Run Code Online (Sandbox Code Playgroud)
这在自 IE6 以来的所有浏览器中都能很好地工作,并且您可以省去一些麻烦,例如在标记中混淆引号。=]
它也更容易维护,以后你甚至可以将页面的 JS 移动到一个单独的.js文件中,用于缓存和分离结构和行为。