window.location.href 不起作用,它总是返回警报



我一直在空闲时间学习HTML/CSS/JS。我仍然是一个菜鸟,我在练习时遇到了这个问题。我想创建一个表单,您可以在其中键入要搜索的内容,sumbit 按钮会将您重定向到 google,如果它为空,它会显示警报。但是重定向不起作用,我总是收到警报。你能指导我我在做什么工作吗?对不起我的英语,这不是我的母语。

<form id="myform">
        <input type="search" name="searchedValue">
        <input type="submit" value="Szukaj">
</form>

<script>
    $("document").ready(function() {
        $("#myform").submit(function(e) {
            var searchedValue = $("input[name='searchedValue']").attr("value");
            if (searchedValue) {
                window.location.href = "http://www.google.pl/#hl=plf&output=search&q="+searchedValue;
            } else {
                alert("empty string");
            }
            e.preventDefault();
        });
    });
</script>
var searchedValue = $("input[name='searchedValue']").val() 

你应该使用val()而不是 attr()。其余的事情都很好。

<form id="myform">
        <input type="search" name="searchedValue">
        <input type="submit" value="Szukaj" onclick="search(event)">
</form>
<script>
    function search(event) {
        // [0] gets the first textbox of current page with name.
        var searchedValue = document.getElementsByName('searchedValue')[0].value;
        if (searchedValue && event) {
            event.preventDefault(); // cancels the event if it is cancelable
            var specs = "height=auto,width=auto";
            var searchUrl = "http://www.google.pl/#hl=plf&output=search&q=" + searchedValue;
            window.open(searchUrl, "_blank", specs);
        } else {
            alert("empty string");
        }
    };
</script>

有用的链接,如window.open()和preventDefault()。我认为在学习时最好使用纯 JavaScript 和 DOM 操作进行练习。无论如何,继续努力。:)

代码很好,我认为您的浏览器阻止了您的重定向

http://www.google.pl/#hl=plf&output=search&q="+searchedValue;

当您拥有https网站并想重定向到http时,可能会发生这种情况。控制台将以静默方式显示有关不安全重定向的错误。

最新更新