在Javascript / jQuery中,如何检查字符串的特定部分并确定它是空格还是字母? [英] in Javascript/jQuery, how to check a specific part of a string and determine if it is a whitespace or letter?

查看:51
本文介绍了在Javascript / jQuery中,如何检查字符串的特定部分并确定它是空格还是字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个函数,当我点击HTML中的字符串(或句子)的任何地方时,它会告诉我这是一个字母还是一个空格。这甚至可能吗?例如,我点击这句话中的任何地方:

I want to write a function where, when I click anywhere on a string (or sentence) in HTML, it will tell me if that is a letter or a whitespace. Is this even possible? For example, I click on anywhere inside this sentence:

<div id='sentence'>The cat in the hat.</div>

假设我点击cat中的字母a。我希望它返回一个警告告诉我,我点击了一个角色。假设我点击cat和in之间的空格。我希望它返回一个警告,说我点击了一个空格。

Say I click on the letter "a" inside "cat". I want it to return an alert telling me that I clicked on a character. Say I click on the whitespace between "cat" and "in". I want it to return an alert saying that I clicked on a whitespace.

这听起来可能不可能,但我有一个想法就是你可能点击某个地方并检查左边你点击的地方的权利(例如,你在空格和字母之间点击),如果至少有一个字符是空格(比如说左边),它应该返回你点击的空格......这会更容易实现吗?我只需要一些建议。

It may sound impossible but one idea I have is that maybe you click somewhere and check to the left and right of where you clicked (for example, you clicked right between a whitespace and a letter), and if at least one of characters is a whitespace (say to the left), it should return that you clicked on a whitespace... would this be easier to implement? I just need some advice on this.

推荐答案

工作示例@ http://jsfiddle.net/Kai/k4YMS/

function clickify (e) {
    var arr = e.innerText.split("") || e.textContent.split(""),
        max = arr.length,
        i = 0,
        template = "<span onclick='alert(this.innerText || this.textContent);'>$c</span>",
        result = "";

    for (; i < max; i += 1) {
        result += template.replace("$c", arr[i]);
    }

    e.innerHTML = result;   
}

这篇关于在Javascript / jQuery中,如何检查字符串的特定部分并确定它是空格还是字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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