单击“使用jQuery”选择/取消选择“文本” [英] Select/Unselect Text on click Using jQuery

查看:124
本文介绍了单击“使用jQuery”选择/取消选择“文本”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在IE9中创建以下行为:

I want to create the following behavior in IE9:

单击文本框将从文本框中选择文本。再次单击它将取消选择文本。

Clicking on the textbox will select the text from the textbox. Clicking on it again will unselect the text.

我尝试了以下内容: http://www.codingforums.com/showthread.php?t=105530

var x = 2;

function selectIt(obj)
{
    if (x % 2 == 0)
    {
        obj.select();
    }
    else
    {
        if (document.selection)
        {
            document.selection.empty();
            obj.blur();
        }
        else
        {
            window.getSelection().removeAllRanges();
        }
    }
    obj.focus();
    x++;
}

我也用过: http://jsfiddle.net/HmQxZ/1/

但上述解决方案很奇怪应用于多个文本框时的行为。解决此类问题的最佳方法是什么?是否可以在不使用全局变量的情况下执行此操作?

But the above solutions have weird behaviors when applied to several textboxes. What is the best way to approach this kind of problem. Is it possible to do this without using a global variable?

更新:

小提琴在Chrome中有效。但它在IE9中不起作用。在IE9中,文本被选中,但是当您再次单击文本框时,文本不会被取消选中/不突出显示。在Chrome中,第二次点击取消选择/取消突出显示文字。

The fiddle works in Chrome. But it does not work in IE9. In IE9, the text is selected but when you click on the textbox again, the text is not unselected/unhighlighted. In Chrome, the second click unselects/unhighlights the text.

谢谢。

推荐答案

几个文本框的问题是你的 x 变量是全局的。每个文本框需要一个单独的 x 变量。

The problem with several text boxes would be that your x variable is global. You'd need a separate x variable per textbox.

您可以使用地图:

var x = {};

function selectIt(obj)
{
    var key = ... <-- get name (or id) of textbox from obj somehow to use as key in map
    if (!x.hasOwnProperty(key)) x[key] = 0;
    if (x[key] % 2 == 0)
    {
        obj.select();
    }
    else
    {
        if (document.selection)
        {
            document.selection.empty();
            obj.blur();
        }
        else
        {
            window.getSelection().removeAllRanges();
        }
    }
    obj.focus();
    x[key]++;
}

这篇关于单击“使用jQuery”选择/取消选择“文本”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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