0

我需要清空并专注于按键输入的 textarea。我想我写了正确的代码,但有时 textarea 变空但没有焦点发生,有时发生焦点但没有运气清空这个对象。我使用了许多不同的代码,但使用没运气。

这是我的js:

<script>
$(document).ready(function() {
    $("#data").focus(function() {
    $(this).empty();
    $(this).focus();
    });
})


    // when the client hits ENTER on their keyboard
    $('#data').keypress(function(e) {


    $this = $(this);
    if($this.val().length == 1)
    {
        var x =  new RegExp("[\x00-\x80]+"); // is ascii

        var isAscii = x.test($this.val());

        if(isAscii)
        {
           $("#data").css({"direction": "ltr", "text-align": "left"});
        } else {
            $("#data").css({"direction": "rtl", "text-align": "right"});
        }
    }


        if (e.shiftKey && e.keyCode == 13) {
            $(this).val($(this).val() + "\n");
            return;

          }
            if(e.which == 13) {
                if($this.val().length == 0){
                    alert('your value is empty')
                }

                var now = time();
                if(now+0.5 > counter){
                counter = now;
                $(this).blur();
                $('#datasend').focus().click();
            }else{
            }
            }
        });
    });

这是我的html部分:

    <div class="wrap">
    <div class="rooms">
    <div class="clear"></div>
        <div class="roomsicon">
chatrooms
        </div>
        <ul id="rooms">
        </ul>
    </div>
    <div class="chat_box_container">
    <div class="chat_box" id="mydiv">
    <div id="conversation"></div>
    </div>
    <div class="input_field">
        <textarea id="data" placeholder="type your text ... " ></textarea>
        <input type="button" id="datasend" value="send" />
    </div>

    </div>
    <div class="users">
        <div class="usersicon">online users </div>

        <ul id="users">
        </ul>
    </div>

    </div>
    <!-- clear float -->
    <div class="clear"></div>
4

3 回答 3

1

empty()不会删除该值。

.val("");

您基本上是在焦点事件中调用焦点导致无限循环。不好。

$("#data").focus(function() {
    $(this).val('');
});

另外,您为什么要重新发明元素上已有的 HTML5 占位符属性?

于 2013-05-07T13:13:22.900 回答
0

有一个 autofocus html5 标签(布尔值,不需要值),它会自动将焦点放在它设置的任何输入/文本区域上:http ://www.html5tutorial.info/html5-autofocus.php

这里有很多 js 后备代码:http: //sampsonblog.com/tag/html5

想象一下,如果 js 可用,跨浏览器兼容的表单输入上的自动对焦,如果 js 不可用,启用 HTML5 的浏览器仍然显示自动对焦.. 现在你唯一缺少的是“按键”自动对焦,如果你肯定需要这个功能,所以你需要使用回车键触发上面的代码,执行自动对焦似乎更优雅,虽然我知道它会让禁用用户不控制他们的光标在页面上的位置,所以键执行可能是从这个角度来看更好,但是如果禁用的用户难以导航,那么有一种方法可以禁用自动对焦属性,所以不用担心太多..

html5 的 accesskey 属性正在讨论中,它被删除但又被占用了,这将是使用键将焦点集中到表单元素的最佳方式,但正如我所说,它正在讨论中并且可以再次删除:http:/ /lists.w3.org/Archives/Public/public-html-a11y/2010Jul/0103.html

于 2013-05-07T14:03:45.583 回答
0

您的代码中没有 ID 为“data”的元素。此外,当焦点不在元素内部时,您正在绑定keypress当然不会触发的 #data-element 。尝试将事件绑定到文档而不是文本区域。

于 2013-05-07T13:16:06.563 回答