单击时确定一个句子的字符 [英] Determining a character of a sentence when clicked on

查看:72
本文介绍了单击时确定一个句子的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在随机休息时,我发现自己想知道是否可以在点击时使用jQuery来确定单个字符。

On a random break I found myself wondering if it would be possible to use jQuery to determine a single character within a sentence when it is clicked on.

例如:
这个

当用户点击第一个 h ,jQuery会将这个返回给我。

When the user clicks on first h, jQuery would return this to me.

我能想到的唯一方法就是将每个字符用一个span它的字母类如下面的例子:

The only way I could think of doing this would be to wrap each character within the sentence in a span with a class of its letter such as the following example:

<span class="clickable T">T</span>
<span class="clickable h">h</span>
<span class="clickable i">i</span>
<span class="clickable s">s</span>

紧接着 $('。clickable')。click(function( ))会返回它的第二个类。

Followed by a $('.clickable').click(function()) that would return its second class.

我的问题是:这是否是最有效的方法?

My question is: is this the most efficient way to do this?

推荐答案

显然,在span标签中包装文档的每一个字母都不是很有效。

Obviously wrapping every single letter of the document in span tags is not efficient.

至少我能够在Chrome中运行一些东西。基本上,当你点击一个字母时,它会触发双击来选择单词。我们得到的选择实际上给了我们整个目标元素的文本。从那里,我们得到了被点击的信件。我们删除了选择并按照我们的要求去做。

I was able to spin something up that works in Chrome at least. Basically, when you click on a letter, it then triggers a double clicks which selects the word. We get the selection which actually gives us the text of the entire target element. From that, we get the letter that was clicked. We remove the selection and do what we want with the letter.

小提琴在这里

$(function(){
    $(document).click(function(e){
        var target = e.target;
        $(target).dblclick();    
    }).dblclick(function(){
        var selection,
            node,
           text,
           start,
           end,
           letter;

        if (window.getSelection) {
            selection = document.getSelection();
            node = selection.anchorNode;

            if (node.nodeType === 3) {
                text = node.data;
                start = selection.baseOffset;
                end = selection.extentOffet;

                if (!isNaN(start)) {
                    letter = text.substr(start, 1);
                }
            }
            window.getSelection().removeAllRanges()
        } else if(document.selection) {
            //continue work here
        }

        if (letter) {
            alert(letter);
        }

    });
});

这篇关于单击时确定一个句子的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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