我有这段代码可以自动选择输入字段中的文本。
onclick="this.focus();this.select()"
我是这样实现的
<input type="text" onclick="this.focus();this.select()" value="xxxxx">
我认为,如果我全局应用此代码而不是内联应用此代码,更新会更干净、更容易。
如何将此代码从外部 .js 文件添加到所有文本输入标记(或者可能具有特定 ID 的文本输入标记)?
最佳答案
作为<input />
元素会自动聚焦于单击该元素,您应该只需要 this.select()
:
$('input[type="text"]').on('click', function () {
this.select();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="something" />
<input type="text" value="something else" />
<input type="text" value="something other" />
而且,如果您想避免使用 jQuery,您可以简单地:
function selectThis () {
return this.select();
}
Array.prototype.forEach.call(document.querySelectorAll('input[type=text]'), function (input) {
input.addEventListener('click', selectThis);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="something" />
<input type="text" value="something else" />
<input type="text" value="something other" />
引用文献:
-
JavaScript:
-
Array.prototype.forEach()
. -
document.querySelectorAll()
. -
Function.prototype.call()
. -
HTMLInputElement.select
. - jQuery:
-
on()
.
-
关于javascript - 将函数应用于所有文本输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27346993/