问题
I am following this link Find out the 'line' (row) number of the cursor in a textarea. I want to store the line number of all the occurence of "{" in array while user write in textarea. I want to display the array content after it.
Here is source code , I have tried:
<textarea rows="10" cols="100" id="editor" onkeypress="hello(event);" ></textarea>
<div id="lineNo"></div>
<script>
function hello(e)
{
var keyp=e.charCode;
var c=0,i;
var arr=new Array();
if(keyp=='123')
{
var arr[c++]=getLineNumber();
}
for (i=0;i<arr.length;i++)
{
document.getElementById("lineNo").innerHTML="Array content is... "+ arr[i];
//document.write(arr[i] + "<br >");
}
}
function getLineNumber() {
var textarea=document.getElementById("editor")
var x=textarea.value.substr(0, textarea.selectionStart).split("\n").length;
return x;
}
</script>
But array content is not displaying. Please suggest me what is wrong in code and also if possible please tell me a better way to store the line number of all the occurence of particular character in javascript and display it.
回答1:
Is this something you want to do:
<textarea rows="10" cols="100" id="editor" onkeypress="hello(event);" ></textarea>
<div id="lineNo"></div>
<script>
var arr = [];
var c = 0;
function hello(e) {
var keyp=e.charCode;
if(keyp=='123') {
arr[c++] = getLineNumber();
}
document.getElementById("lineNo").innerHTML=
"Array content is... "+ arr.join(' ');
}
function getLineNumber() {
var ta=document.getElementById("editor")
var x=ta.value.substr(0, ta.selectionStart).split("\n").length;
console.log(x)
return x;
}
</script>
来源:https://stackoverflow.com/questions/54178687/storing-the-line-number-of-all-the-occurrence-of-particular-character-in-javascr