OnClick Index in String
Similar to what I asked in this question a while back about getting the index of string onClick
with Android, I would like to now do the same thing with JavaScript (I'm using the jQuery library if there's any useful functions for me in there as well). I've searched online and Stack Overflow and can't seem to find anything. My answer in the question I linked deals with (x,y) coordinates and an offset, which I noticed jQuery has, but it seems to give the position of the entire element relative to the document and not the actual (x,y) coordinates. Is there a similar method of getting the (x,y) coordinates with JavaScript (or an even easier way to get the index onClick)? If my question isn't cl开发者_如何学JAVAear enough, given the following String:
Mary never went to school. Mary was way too cool.
I want to have it so that I can get back 3 if someone clicks on the 'y' in the first "Mary" and so on.
As always, any help or a solid direction is greatly appreciated.
If the text is short enough, it wouldn't be horrible to wrap each letter in its own <span>
.
Something like:
var text = $("#clickable-letter-div").html();
var wrapped = $.map(text.match(/./g), function(s, idx){
return "<span class='letter'>" + s + "</span>"
}).join("");
$("#clickable-letter-div").html(wrapped);
$(".letter").click(function(){
var pos = $(this).parent().children().index(this);
alert(pos);
});
精彩评论