我正在尝试使用javascript/jquery查找文本索引,但我没有得到确切的解决方案。
假设文本是这样的.
Hi all. hello world. Hi all. Hello world.Hi all. hello world. Hi all. Hello world.Hi all. hello world. Hi all. Hello world.Hi all. hello world. Hi all. Hello world.Hi all. hello world. Hi all. Hello world.Hi all. hello world. Hi all. Hello world.Hi all. hello world. Hi all. Hello world.Hi all. hello world. Hi all. Hello world.Hi all. hello world. Hi all. Hello world.Hi all. hello world. Hi all. Hello world.我怎样才能得到选中的“Hello”单词在任何一行上的确切位置?我尝试过indexOf,但它给了我第一个hello文本索引。请任何人对此提出解决方案。
提前谢谢。
发布于 2013-01-04 13:45:26
你可能想看看这个http://help.dottoro.com/ljkstboe.php
$(document).mouseup(function(){
selection = window.getSelection();
index = selection.anchorOffset;
console.log(index);
});演示:http://slackware.koding.com/getSelDemo.html
发布于 2013-01-04 13:42:11
尝尝这个
var foo="yourstring";
var pos = foo.indexOf("Hello");
while(pos > -1) {
document.write(pos + "<br />");
pos = foo.indexOf("Hello", pos+1);
}这是fiddle
发布于 2013-01-04 13:50:50
我不确定为什么indexOf不能为您工作。对我来说也是一样。请检查下面的小提琴。
HTML
<p id="demo">Click the button to locate where in the string a specifed value occurs. </p>
<input type="button" id="btn" value="click"/>脚本
$('#btn').click(function(){
var str="Hello world, hello to the universe.";
var n=str.indexOf("hello");
alert(n)
});Demo
https://stackoverflow.com/questions/14151630
复制相似问题