jQuery专注于输入/ textarea的内容 – 在IE8中无法正常工作

我希望我的网站上的输入字段在用户第一次点击它们时选择所有文本,但在IE8中,文本被选中一瞬间然后恢复正常。 在FF中工作正常。

我的js代码:

$(document).ready(function () { //HTML DOM document is ready // Add this behavior to all text fields $("input[type='text'], textarea").live("focus", function(){ // Select field contents this.select(); }); }); 

有任何想法吗? 我尝试在“.select()”之后添加“.focus()”并且奇怪的是它可以工作,但是在FF和IE中抛出了大量的js错误。

谢谢

在jQuery对象而不是DOM元素上尝试.select() ,并将事件更改为click 。 当您选中该字段时,默认情况下应选择该文本。

 $("input[type='text']").live("click", function(){ // Select field contents $(this).select(); }); 

好吧,这个因为某种原因在后面踢我。 我可以发誓我以前做过这个,但无法弄清楚如何。

这是我想出的最好的。 它使用setTimeout()推迟.select()直到click事件触发为止。 也许有更好的方法? 希望能帮助到你。

 $('input[type=text]').live('focus', function() { var $th = $(this); setTimeout(function(){$th.select();}, 50); });