我正在尝试使用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文本索引。 请任何一个建议的解决方案。
提前致谢。
答案 0 :(得分:1)
您可能需要查看http://help.dottoro.com/ljkstboe.php
$(document).mouseup(function(){
selection = window.getSelection();
index = selection.anchorOffset;
console.log(index);
});
答案 1 :(得分:0)
试试这个
var foo="yourstring";
var pos = foo.indexOf("Hello");
while(pos > -1) {
document.write(pos + "<br />");
pos = foo.indexOf("Hello", pos+1);
}
这是fiddle
答案 2 :(得分:0)
我不确定为什么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)
});