开发者

jQuery if new line, add +1 to line count

开发者 https://www.devze.com 2023-01-17 09:39 出处:网络
I am making a javascript code editor online, and right now I\'m doing the line count on the left side of the editor. 开发者_Python百科I can\'t figure out how to make it so when a new line is created,

I am making a javascript code editor online, and right now I'm doing the line count on the left side of the editor. 开发者_Python百科I can't figure out how to make it so when a new line is created, it adds +1 to the line count, so each new line it it will have the line number on the left. Anyone know a good way to do this?


You can use string.split() to split each occurrence into an array, then get the array count.

$('textarea').keyup(function() {
    if ($(this).val().lastIndexOf('\n')!=-1)
        x = $(this).val().split('\n');
    $('div').text(x.length); // This will be the line number
});​

Fiddle

http://jsfiddle.net/WkVb9/


Count the number of \n instances in a string, and apply it recursively to the left side div that contains the numbers.


Check each input, if it is a \n, just + 1. Hope to see a better answer...

0

精彩评论

暂无评论...
验证码 换一张
取 消