2013-04-01 2 views
0

Я пытаюсь закрыть тег с помощью javascript, но когда он записывает в документ, косая черта всегда отсутствует. Я пробовал перед ним обратную косую черту («\ /»), но, похоже, это помогает. Я продолжаю видеть <pre> на источнике страницы. Вот код:закрытие тега с помощью javascript

var temp_index = 0, 
    line_count = 0; 
while (temp_index < text.length) { 
    if ((text.charAt(temp_index) == "\n") && (line != line_count)) { 
     if (line_count < line) line_count++; 
     if (line_count == line) { 
      text = text.substring(0, temp_index) + "<pre id='line'>" + text.substring(temp_index); 
      temp_index++; 
      while ((text.charAt(temp_index) != "\n") && (temp_index < text.length)) temp_index++; 
      text = text.substring(0, temp_index - 1) + "<\pre>" + text.substring(temp_index); 
     } 
    } 
    temp_index++; 
} 
return text; 

Я ожидал получить:

Heres's the last line 
<pre id='line'>Here's the current line</pre> 
Here's the next line 
Here's the final line 

Но я получаю:

Here's the last line 
<pre id='line'>Here's the current line 
Here's the next line 
Here's the final line</pre> 

Я сделал быстро исправить, заменив \ п на конец строки с тегом. Несмотря на то, что проблема устранена, она вызывает ошибки при вводе клавиатуры. Вот обновленный код.

if (line_count == line) { 
    text = text.substring(0, temp_index) + "<pre id=\"line\">" + text.substring(temp_index); 
    temp_index++; 
    while ((text.charAt(temp_index) != "\n") && (temp_index < text.length)) temp_index++; 
    text = text.substring(0, temp_index - 1) + "</pre>" + text.substring(temp_index); 
    break; 
} 
+0

попытался с помощью '// '? –

+0

Да, я просто сделал, я все еще вижу < pre> – tay10r

+2

Вам не нужно скрывать косую черту, поэтому «//» фактически равно «//». Обратные косые черты - другая история, поэтому, если у вас есть «\\» в строке, это приведет к «\». – doublesharp

ответ

1

Этот код синтаксически корректен - инициализирует temp_index и text и опускает break вне цикла:

temp_index = 0; 
text = "this is \n a test \n of some info"; 

text = text.substring(0, temp_index) 
    + "<pre id=\"line\">" 
    + text.substring(temp_index); 

temp_index++; 

while((text.charAt(temp_index) != "\n") && (temp_index < text.length)) temp_index++; 

text = text.substring(0, temp_index - 1) 
    + "</pre>" 
    + text.substring(temp_index - 1); 

alert(text); 

Результаты в

<pre id="line">this is</pre> 
a test 
of some info 

Вы также можете использовать replace переписать текущей линии и получить тот же результат, что и выше:

text = "this is \n a test \n of some info"; 
text = text.replace(/(.+?)\n/, "<pre id=\"line\">$1</pre>\n"); 

Если вы знаете текущую строку и хотите предварять его <pre id=\"line\"> и добавить его с </pre Я хотел бы использовать split() и join():

// update line 2 
line = 2; 

// sample text 
text = "this is\n"+ 
     "a test\n"+ 
     "of some info"; 

// split to an array on newlines 
vals = text.split("\n"); 

// replace the second line, which has an index of 1 (or line-1) 
vals[line-1] = "<pre id=\"line\">" + vals[line-1] + "</pre>"; 

// join back to an array using newlines 
text = vals.join("\n"); 

Результат:

this is 
<pre id="line">a test</pre> 
of some info 
+0

. Я обновил код, чтобы показать родительский цикл while, и что я уже инициализировал temp_index и line_count – tay10r

+0

содержит переменную 'text', содержащую текущую строку? – doublesharp

+0

содержит много строк, включая ток. И строка, которая должна быть выделена, указана в строке «441». – tay10r

Смежные вопросы