Home > OS >  HTML line break inside a <script> for a function
HTML line break inside a <script> for a function

Time:12-31

Within a I create another with a function inside. The function requires a line break so that it is "recognized". If I use <br /> the function is recognized but Javascript gives the error "Uncaught SyntaxError: Unexpected token '<'". How do I make a linebreak that it is recognized in HTML but not recognized as an error by js?

//good for html and bad for js cause the error pops up
downloadfunction.innerHTML = 'function download'   i   '(){**<br />**document.getElementById("delcon'    i   '").checked = true;}';

//bad for html and good for js (But here the function does not work because it is not recognized as a function.)
downloadfunction.innerHTML = 'function download'   i   '(){document.getElementById("delcon'    i   '").checked = true;}';

//stuff like \n isnt working

I tried to create a function in a loop with variable function names (hence the "i") in a . The loop is also in a due to other reasons and cannot be swapped out.

CodePudding user response:

You can use normal line breaks inside a Javascript string if it is delimited by `...`. The following snippet illustrates what can be done:

var i = 1;
document.getElementById("downloadfunction").textContent = `function download${i}() {
  document.getElementById("delcon${i}").checked = true;
}`;
<script id="downloadfunction"></script>
<input id="delcon1" type="checkbox"/>
<button onclick="download1()">Check</button>

But as Quentin pointed out in the comment, rather than generating functions download1(), download2(), consider using one function with a parameter download(i).

  • Related