使用jQuery选择所有焦点文字 [英] Select all text on focus using jQuery

查看:65
本文介绍了使用jQuery选择所有焦点文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jQuery小功能,当它获得焦点时,它会自动在asp.net文本框中选择文本.但是,文本框中的文本被选中,但随后立即取消选择.

I have a little jQuery function that is meant to automatically select text in an asp.net text box when it gets focus. However, the text in the text box gets selected, but immediately then deselects.

如果我使用.focus(function())绑定到焦点事件,则代码可以正常工作,但是我将文本框动态添加到页面中,这就是为什么我认为需要使用实时事件的原因.

The code works if i bind to the focus event with .focus(function()) but I am adding the text boxes to the page dynamically which is why I think I need to use the live event.

有人可以看到问题吗?有问题的文本框是否在多视图内部的两个网格视图的项目模板中?

Can anyone see a problem? The text boxes in question are in Item templates of two gridviews inside a multiview if that makes a difference?

代码:

<script type="text/javascript">

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

    });

</script>

<script type="text/javascript">

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

    });

</script>

推荐答案

似乎是mouseup事件的干扰.您会发现,如果单击并按住表单字段,然后将其移到"mouseup"选择栏中.使用mouseup而不是focus来触发select()方法似乎很好:

It seems to be the mouseup event interfering. You'll notice if you click and hold in the form field then move outside of it to "mouseup" the selection sticks. Using mouseup instead of focus to trigger the select() method seems to work well:

<script type="text/javascript">

    //Select all text in Cost Rate Text Boxes when they have focus
    jQuery(function($){
        $("table.demo").on("mouseup", ".CostRateTextBox", function () {
            $(this).select();
        });
    });

</script>

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

有关jQuery 1.3-1.8兼容代码,请参见原始演示.

Demo: jsfiddle.net/gableroux/jvJzX/12

See original demo for jQuery 1.3 - 1.8 compatible code.

这篇关于使用jQuery选择所有焦点文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆