是否有可能获得文本区域内字符串的每个单词的数量。比如,文本区域内的'I Like Apple'字符串,当我点击'I'它应该给出0,' Like ' ->1和'Apple' ->2. 不是字母聪明,而是单词聪明。
<textarea>I like Apple</textarea>
您可以根据字符串查找单词编号/索引:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="text" id="checktext" value="This is the string to check words index" />
JS代码:
$(document).ready(function() {
$("#checktext").on('click', function(e) {
var text = document.getElementById("checktext").value,
element = $("#checktext")[0],
arr1 = text.split(" "),
length = 0,
selectIndex = element.selectionStart;
if (selectIndex == 0){
console.log(arr1.indexOf(arr1[0]));
}
else {
for (var i = 0; i < arr1.length; i++) {
length = length + arr1[i].length + 1;
if (length == selectIndex) {
console.log(i + 1);
break;
}
}
}
});
});
希望这解决了你的问题!