简体   繁体   English

使用jQuery突出显示(选择)文本框中的所有文本

[英]Using jQuery to Highlight (Select) All Text in a Textbox

我有一个带有一些文本的输入文本框,onclick事件我想运行一个javascript函数来选择(突出显示)此框中的所有文本,我如何用jquery做到这一点?

No need for jQuery, this is simple with the DOM and works in all mainstream browsers: 不需要jQuery,这对于DOM很简单,适用于所有主流浏览器:

input.onfocus = function() { this.select(); };

If you must do it with jQuery, there's very little difference: 如果你必须使用jQuery,那么差别很小:

$(input).focus(function() { this.select(); });

You may take a look at this article : 你可以看一下这篇文章

Let's assume that we have the following text input: 我们假设我们有以下文本输入:

 <input type="text" id="txtInput" /> 

In most cases, we would want to have this feature available to all textboxes across our website, so we would create a function to handle this, and call it as needed. 在大多数情况下,我们希望将此功能提供给我们网站上的所有文本框,因此我们将创建一个处理此功能的函数,并根据需要调用它。 Calling this function with the expected argument will make execute the highlighting of the text. 使用期望的参数调用此函数将使执行突出显示文本。

 function selectAllText(textbox) { textbox.focus(); textbox.select(); } 

Assuming you are developing against DotNetNuke 5, or have jQuery already imported into your website, add the following jQuery to your site for each textbox. 假设您正在开发针对DotNetNuke 5,或者已将jQuery导入您的网站,请为您的网站添加以下jQuery以用于每个文本框。 (If you have a lot of textboxes, we could do this differently, but that's for a different post.) (如果你有很多文本框,我们可以采用不同的方式,但这是针对不同的帖子。)

 jQuery('#txtInput').click(function() { selectAllText(jQuery(this)) }); 

You can do this: 你可以这样做:

$('input').click(function() {
 // the select() function on the DOM element will do what you want
 this.select();
});

Of course, then you can't click on the element to select an arbitrary point in the input, so it might be better to fire that event on focus instead of click 当然,那么你不能点击元素来选择输入中的任意一个点,所以最好在focus上触发该事件而不是click

Quick Demo w/ click or w/ focus 快速演示w /单击w /焦点

这对我来说效果最好。

$('myTextbox').select();

I know this isn't jquery, but for completeness of the answers to this question, you can use this on the text input itself: 我知道这不是jquery,但是为了完整地回答这个问题,你可以在文本输入上使用它:

 onclick="this.select();"

For example: 例如:

<input type="text" value="abc" onclick="this.select();"/>

Where I typically do this is in 我通常这样做的地方是

$(document).ready(function () {
    $('#myTextBox').focus();
    $('#myTextBox').select();
}

for the first textbox that I want filled in. That way if I'm preserving state; 对于我想填写的第一个文本框。如果我保留状态那样; and if the user backtracks to the page then it automatically highlights it all for typeover. 如果用户回溯到该页面,则会自动突出显示所有内容以进行切换。

Useful technique for things like search boxes... 搜索框之类的有用技巧......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM