location.href的Javascript问题 [英] Javascript problem with location.href

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

问题描述

我有一个文本框,每当用户按下某个键时,都会对其进行检查以查看用户是否按下了回车键.如果按下Enter键,我想在文本框中添加所有信息,然后将用户转移到其他网址.

I have a textbox and whenever the user presses a key it's checked to see if the user pressed enter. If the enter key is pressed, i want to add all the info in the textbox and transfer the user to a different url.

<script language="javascript" type="text/javascript">
    function checkEnter(e){ //e is event object passed from function invocation
        var characterCode;

        if(e && e.which){ //if which property of event object is supported (NN4)
            e = e;
            characterCode = e.which; //character code is contained in NN4's which property
        }
        else{
            e = event;
            characterCode = e.keyCode; //character code is contained in IE's keyCode property
        }

        if (characterCode == 13) { //if generated character code is equal to ascii 13 (if enter key)
            var searchLink = '/Search/?Keywords=' + document.getElementById('<%= searchBox.ClientID %>').value;

            transferUser(searchLink);         
            return false; 
        }
        else{
            return true; 
        }
    }

    function transferUser(url) {
        window.location.href = url;
        window.location.replace(url);   
    }
    </script>

Search: <input name="ctl00$searchBox" type="text" id="ctl00_searchBox" class="header_line_search_box_textbox" onKeyPress="checkEnter(event);" />

我尝试了所有可能的组合,但没有任何反应.该网站会自动刷新.

I have tried every possible combination, but nothing happens. The site just refreshes itself.

我还需要某种方式将文本从用户转换为html安全,必须像aspx中的HttpUtility.EncodeUrl.

I also need somehow to convert the text from the user to html safe, must like the HttpUtility.EncodeUrl in aspx.

推荐答案

我不确定您是否需要所有这些.以下HTML标记的常规内置行为完全可以实现您所需的功能,而无需使用任何JavaScript:

I'm not sure you need all of this. Normal, built-in behavior for the following HTML markup does exactly as you want without the need for any JavaScript:

<form method="get" action="/Search/">
    <input type="text" name="Keywords">
</form>

但是,重要的是您的UI必须采用某种方式提交不涉及按键的表单.这有两个原因:

However, it is important that your UI have some sort of way to submit the form that doesn't involve a key stroke. This is for two reasons:

  1. 正如Jorn所指出的那样,密钥提交表单可能并不容易.
  2. 没有提交按钮可能会破坏使用其他输入设备的用户的可用性.

由于上述原因,建议采取以下措施:

Because of the above reasons, the following is suggested:

<form method="get" action="/Search/">
    <input type="text" name="Keywords">
    <input type="submit" value="Search or 'go' or whatever">
</form>

这篇关于location.href的Javascript问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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