我使用这段代码尝试在用户聚焦于字段时选择字段中的所有文本。发生的事情是,它选择了所有的一秒钟,然后它被取消选择,输入光标留在我点击的地方…

$("input[type=text]").focus(function() {
   $(this).select();
});

我希望一切都能被选中。


当前回答

<script>$.ready( $("input[type=text]").attr("onclick" , "this.select()"));<script>

其他回答

这个版本适用于ios,也修复了windows chrome上的标准拖拽选择

var srcEvent = null;

$("input[type=text],input[type=number]")

    .mousedown(function (event) {
        srcEvent = event;
    })

    .mouseup(function (event) {
        var delta = Math.abs(event.clientX - srcEvent.clientX) 
                  + Math.abs(event.clientY - srcEvent.clientY);

        var threshold = 2;
        if (delta <= threshold) {
                   try {
                        // ios likes this but windows-chrome does not on number fields
                        $(this)[0].selectionStart = 0;
                        $(this)[0].selectionEnd = 1000;
                    } catch (e) {
                        // windows-chrome likes this
                        $(this).select();
                    }
        }
    });

http://jsfiddle.net/Zx2sc/2/

你可以使用简单的代码:

$('#idname').select();

试着用点击代替聚焦。它似乎对鼠标和键事件都有效(至少在Chrome/Mac上):

jQuery < 1.7版本:

$("input[type='text']").click(function () {
   $(this).select();
});

jQuery 1.7+版本:

$("input[type='text']").on("click", function () {
   $(this).select();
});

这是一个演示

这里有一些不错的答案,@user2072367是我最喜欢的,但当你通过标签而不是通过点击关注时,它会产生意想不到的结果。(意想不到的结果:通过标签聚焦后正常选择文本,必须再点击一次)

这个小提琴修复了这个小错误,并额外将$(This)存储在一个变量中,以避免多余的DOM选择。点击这里查看详情!(:

在IE >中测试

$('input').on('focus', function() {
    var $this = $(this)
        .one('mouseup.mouseupSelect', function() {
            $this.select();
            return false;
        })
        .one('mousedown', function() {
            // compensate for untriggered 'mouseup' caused by focus via tab
            $this.off('mouseup.mouseupSelect');
        })
        .select();
});

我使用FF 16.0.2和jquery 1.8.3,所有的代码在答案不工作。 我使用这样的代码工作。

$("input[type=text]").focus().select();