开发者

in Javascript/jQuery, how to check a specific part of a string and determine if it is a whitespace or letter?

开发者 https://www.devze.com 2023-02-01 11:29 出处:网络
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 in

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>

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 th开发者_开发知识库is be easier to implement? I just need some advice on this.


Working example @ 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;   
}


Not directly possible, but if you take every single character in html elements this can be possible. Here is what i thought:

var $sentence = $("#sentence");
var sentence = $sentence.html();

//we'll use this after we recreate the sentence
function tellMeWhatIAm(){
  //as its name says it tells what it is
  alert($(this).text());
}

$.each(sentence,function(i,t){
  //clear the sentence
  if(i==0) $sentence.html("");
  //create every char again
  //and bind click event to our function above
  var $span = $("<span/>",{"text" : t, "click" : tellMeWhatIAm});
  //append the chars back to the sentence wrapper
  $sentence.append($span);
});

Haven't tested it though, but the idea is pretty straightforward.

Hope it helps, Sinan.


Using Range, no need to modify the html.

  $('#sentence').click(function(e) {
    if (window.getSelection) {
      var cursor = window.getSelection().getRangeAt(0).startOffset 
      var str = e.target.innerHTML;
      alert(str[cursor]);

    } else {
      var range = document.selection.createRange();
      range.expand('character');
      alert(range.text);

    }

  });
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号