简体   繁体   English

Javascript无法在引导输入中正常运行

[英]Javascript doesn't work as expected in bootstrap input

I want to redirect users when they type words and press enter to another page 我想在用户输入单词并按Enter时将其重定向到另一页

<div class="form-group has-feedback">
    <input id="searchbox" type="text" class="form-control" placeholder="search" onkeypress="Fsearchbox(event)" />
    <i class="glyphicon glyphicon-camera form-control-feedback"></i>
</div>

<script>
function Fsearchbox(e) {
    var keynum;

    if(window.event) // IE                  
        keynum = e.keyCode;
    else if(e.which) // Other browsers                  
        keynum = e.which;

    if (keynum==13)
    {
        var x = document.getElementById("searchbox").value;
        window.location.href = '/Mo3taz/public/search/'+x;
    }
}
</script>

The problem is When I type something in the input and press enter the page does't redirect to the new location and shows a question mark after the URL of the current page http://localhost/Mo3taz/public/bio? 问题是当我在输入中键入内容并按Enter时,页面不会重定向到新位置,并且在当前页面的URL http://localhost/Mo3taz/public/bio?之后显示一个问号http://localhost/Mo3taz/public/bio?

What is the reason for that? 是什么原因呢? and how can I solve it? 以及我该如何解决?

From the behavior you describe, I can easily guess that your input is inside a <form> , with a GET method (which adds parameters to the URL after a ? , but your parameters are empty because your input does not have a name attribute). 从您描述的行为中,我可以很容易地猜测到您的输入是在<form>内部,并带有GET方法(该方法将参数添加到URL之后的? ,但是您的参数为空,因为您的输入没有name属性) 。

When you hit enter, the form is submitted, and your redirection is not taken into account. 当您按Enter键时,将提交表单,并且不会考虑您的重定向。 To prevent the form from being submitted and do your redirection via JS, just add e.preventDefault(); 为了防止表单提交并通过JS进行重定向,只需添加e.preventDefault();

Fixed code: 固定代码:

function Fsearchbox(e) {
    var keynum = e.keyCode || e.which;

    if (keynum==13){
        var x = document.getElementById("searchbox").value;
        window.location.href = '/Mo3taz/public/search/'+x;
        e.preventDefault();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM