什么是香草JS或jQuery解决方案,将选择一个文本框的所有内容时,文本框接收焦点?


当前回答

注意:如果你在ASP中编程。NET中,您可以使用ScriptManager运行脚本。c#中的RegisterStartupScript:

ScriptManager.RegisterStartupScript(txtField, txtField.GetType(), txtField.AccessKey, "$('#MainContent_txtField').focus(function() { $(this).select(); });", true );

或者在其他答案中建议的HTML页面中输入脚本。

其他回答

$(document).ready(function() {
    $("input:text").focus(function() { $(this).select(); } );
});

我的解决办法是使用暂停。看起来还行

$('input[type=text]').focus(function() {
    var _this = this;
    setTimeout(function() {
        _this.select();
    }, 10);
});
$('input').focus(function () {
    var self = $(this);
    setTimeout(function () {
        self.select();
    }, 1);        
});

编辑:根据@DavidG的请求,我不能提供详细信息,因为我不确定为什么这样工作,但我相信这与向上或向下传播的焦点事件或任何它所做的事情有关,输入元素获得它所接收的焦点通知。设置timeout会给元素一点时间来意识到它已经这样做了。

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

我有点晚了,但这在IE11, Chrome, Firefox中工作完美,没有混乱的鼠标(没有JQuery)。

inputElement.addEventListener("focus", function (e) {
    var target = e.currentTarget;
    if (target) {
        target.select();
        target.addEventListener("mouseup", function _tempoMouseUp(event) {
            event.preventDefault();
            target.removeEventListener("mouseup", _tempoMouseUp);
        });
    }
});