什么是香草JS或jQuery解决方案,将选择一个文本框的所有内容时,文本框接收焦点?
当前回答
什么是JavaScript或jQuery解决方案,将选择一个文本框的所有内容时,文本框接收焦点?
您只需要添加以下属性:
onfocus="this.select()"
例如:
<input type="text" value="sometext" onfocus="this.select()">
(说实话,我不知道你为什么还需要其他东西。)
其他回答
我的解决方案是:
var mouseUp;
$(document).ready(function() {
$(inputSelector).focus(function() {
this.select();
})
.mousedown(function () {
if ($(this).is(":focus")) {
mouseUp = true;
}
else {
mouseUp = false;
}
})
.mouseup(function () {
return mouseUp;
});
});
因此,鼠标通常会工作,但不会在通过输入获得焦点后取消选择
$('input').focus(function () {
var self = $(this);
setTimeout(function () {
self.select();
}, 1);
});
编辑:根据@DavidG的请求,我不能提供详细信息,因为我不确定为什么这样工作,但我相信这与向上或向下传播的焦点事件或任何它所做的事情有关,输入元素获得它所接收的焦点通知。设置timeout会给元素一点时间来意识到它已经这样做了。
注意:如果你在ASP中编程。NET中,您可以使用ScriptManager运行脚本。c#中的RegisterStartupScript:
ScriptManager.RegisterStartupScript(txtField, txtField.GetType(), txtField.AccessKey, "$('#MainContent_txtField').focus(function() { $(this).select(); });", true );
或者在其他答案中建议的HTML页面中输入脚本。
onclick="this.focus();this.select()"
HTML:
var textFiled = document.getElementById("text-filed"); 文本文件。addEventListener("focus", function() {this.select();}); 输入你的文本:<input type=" Text " id=" Text -filed" value="test with filed Text ">
使用JQuery:
$("#text-filed").focus(function() { $(this).select(); } );
使用React JS:
在各自的组成部分-
<input
type="text"
value="test"
onFocus={e => e.target.select()}
/>
推荐文章
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- jQuery: keyPress退格键不火?
- XMLHttpRequest Origin null不允许Access-Control-Allow-Origin for file:/// to file:///(无服务器)
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔
- TypeScript枚举对象数组
- 在React.js中正确的img路径
- 在React.js中更新组件onScroll的样式