使用jQuery选择焦点上的所有文本

我有一个小jQuery函数,用于在获得焦点时自动选择asp.net文本框中的文本。 但是,文本框中的文本会被选中,但会立即取消选择。

如果我使用.focus(function())绑定焦点事件,代码就可以工作,但是我正在动态地将文本框添加到页面中,这就是为什么我认为我需要使用直播事件。

有谁能看到问题? 有问题的文本框是多视图内两个网格视图的项目模板,如果这有所不同?

码:

 //Select all text in Cost Rate Text Boxes when they have focus $(document).ready(function () { $(".CostRateTextBox").live('focus', function () { $(this).select(); }); });  

在此处输入图像描述

编辑:

  //Select all text in Cost Rate Text Boxes when they have focus $(document).ready(function () { $(".CostRateTextBox").live('focus', function () { $(this).select(); preventDefault(); }); });  

这似乎是mouseup事件的干扰。 您会注意到,如果您在表单字段中单击并按住,然后移动到其外部以“选择”选择棒。 使用mouseup而不是focus来触发select()方法似乎运行良好:

  

演示: jsfiddle.net/gableroux/jvJzX/12

请参阅jQuery 1.3 – 1.8兼容代码的原始演示 。

我在使用的产品搜索表单上遇到了类似的问题。 我知道这已经得到了解答,但我认为提交我的代码不会有什么坏处,对吧?

 $('#product-search').focus(function(){ $('#product-search').mouseup(function(){ $(this).select(function(){ $(this).off('mouseup'); }); $(this).select(); }); }); 

优点是它只在表单首次获得焦点时选择文本,而不是每次单击表单时选择文本,例如当用户想要选择文本的一部分时。

我重写了马塞尔的小提琴,以展示其中的差异。 http://jsfiddle.net/7tDYq/2/

这是我在问题中提出的解决方案jquery输入select all all on focus :

 $("input").focus(function(){ $(this).on("click.a keyup.a", function(e){ $(this).off("click.a keyup.a").select(); }); }); 
 $("input").focus(function(){ $(this).on("mouseup.a keyup.a", function(e){ $(this).off("mouseup.a keyup.a").select(); }); }); // event logger $("input").on("mousedown focus mouseup click blur " + "keydown keypress keyup change", function(e) { console.log(e.type); });